﻿Imports Microsoft.VisualBasic


Public Module Mylib

    Public Function SF(s As String, ParamArray p() As Object) As String

        Return String.Format(s, p)

    End Function



    Public Function FC(ByVal controlID As String) As Control
        Return FC(Of Control)(controlID)
    End Function
    Public Function FC(Of TResult As Control)(ByVal controlID As String) As TResult
        Return FC(Of TResult)(controlID, HttpContext.Current.CurrentHandler)
    End Function
    Public Function FC(ByVal controlID As String, ByVal Parent As Control) As Control
        Return FC(Of Control)(controlID, Parent)
    End Function
    Public Function FC(Of TResult As Control)(ByVal controlID As String, ByVal Parent As Control) As TResult
        Return UI.Controls.FindControl(Of TResult)(controlID, Parent)
    End Function


End Module

Namespace MyApp

    Public Enum LogActionType
        LOGIN = 1
        LOGOUT = 2
    End Enum

    Public Module DataGlobal

        Public DataSimilText As SimilText.ArchiveData
        'Public DataGeo As Geo.Data
        Public DataNet As Dictionary(Of MyApp.Network.AccType, MyApp.Network.NetProperty)
        Public AccountDebug As Integer = Utils.Conv.ToInt(Web.Configuration.WebConfigurationManager.AppSettings("AccountDebug"))

        Public Sub InitApplication()


            MyUI.Routes.RegisterRoutes(Routing.RouteTable.Routes)

            DataNet = New Dictionary(Of MyApp.Network.AccType, MyApp.Network.NetProperty)

            Dim Prop As MyApp.Network.NetProperty

            '----------------------------------------------------------

            Prop = New MyApp.Network.NetProperty
            DataNet.Add(MyApp.Network.AccType.TWITTER_ACCOUNT, Prop)

            '----------------------------------------------------------

            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            DataNet.Add(MyApp.Network.AccType.FACEBOOK_USER, Prop)

            '----------------------------------------------------------


            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            DataNet.Add(MyApp.Network.AccType.FACEBOOK_PAGE, Prop)

            '----------------------------------------------------------

            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            DataNet.Add(MyApp.Network.AccType.LINKEDIN_PEOPLE, Prop)

            '----------------------------------------------------------

            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            DataNet.Add(MyApp.Network.AccType.LINKEDIN_COMPANY, Prop)

            '----------------------------------------------------------

            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            DataNet.Add(MyApp.Network.AccType.GOOGLE_PEOPLE, Prop)

            '----------------------------------------------------------

            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            DataNet.Add(MyApp.Network.AccType.GOOGLE_PAGE, Prop)

            '---------------------------------------------------------
            Prop = New MyApp.Network.NetProperty
            Prop.Available.AccountGeoLocate = False
            Prop.App.SocialSeo = False
            DataNet.Add(MyApp.Network.AccType.BUFFER, Prop)






        End Sub

        Public Sub InitSession()

            'MyApp.SetCurrCountry("IT")

        End Sub

        Public Sub InitLoginUser()

            'MyApp.WriteAppLog(MyApp.LogActionType.LOGIN, 0)

            Dim CurrUser = MyApp.GetUser

            CurrUser.InitUserDataDB()

        End Sub



    End Module


    Public Module LibGlobal

        Public Function RemoveDiacritics(stIn As String) As String
            ' qui un errore che non ho capito
            Dim stFormD As String = ""
            Try
                stFormD = stIn.Normalize(NormalizationForm.FormD)
            Catch ex As Exception

            End Try
            Dim sb As New StringBuilder()

            For ich As Integer = 0 To stFormD.Length - 1
                Dim uc As Globalization.UnicodeCategory = Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD(ich))
                If uc <> Globalization.UnicodeCategory.NonSpacingMark Then
                    sb.Append(stFormD(ich))
                End If
            Next

            Return sb.ToString.Normalize(NormalizationForm.FormC)
        End Function

        'Public Function GetSimilData() As SimilText.ArchiveData

        '    If DataSimilText Is Nothing Then
        '        DataSimilText = New SimilText.ArchiveData
        '    End If

        '    Return DataSimilText

        'End Function


        Public Function PrintList(ByVal dt As DataTable, ByVal Field As String, ByVal Sep As String, ByVal LastSep As String) As String
            Dim l As New List(Of Object)

            For Each dr In dt.Rows
                l.Add(dr(Field))
            Next

            Return PrintList(l, Sep, LastSep)

        End Function

        Public Function PrintList(ByVal l As List(Of Object), ByVal Sep As String, ByVal LastSep As String) As String
            Dim Tmp As String = ""
            For ct As Integer = 0 To l.Count - 1
                Tmp &= l(ct)
                If ct <> l.Count - 1 Then
                    If ct = l.Count - 2 Then
                        Tmp &= LastSep
                    Else
                        Tmp &= Sep

                    End If

                End If
            Next
            Return Tmp

        End Function


        Public Function JSONSerialize(obj As Object) As String
            Dim js As New System.Web.Script.Serialization.JavaScriptSerializer

            Return js.Serialize(obj)

        End Function
        Public Function JSONDeserialize(s As String) As Object
            Dim js As New System.Web.Script.Serialization.JavaScriptSerializer

            Return js.DeserializeObject(s)

        End Function
        Public Function JSONDeserialize(Of t)(s As String) As t
            Dim js As New System.Web.Script.Serialization.JavaScriptSerializer

            Return js.Deserialize(Of t)(s)

        End Function
        Public Function JSONDeserialize(Of t)(s As String, def As t) As t
            Dim js As New System.Web.Script.Serialization.JavaScriptSerializer

            Dim o As t
            Try
                o = js.Deserialize(Of t)(s)
            Catch ex As Exception
            End Try

            If o Is Nothing Then
                o = def
            End If

            Return o

        End Function
        Public Function JSONDeserializeObj(Of t As {New})(s As String) As t

            Return JSONDeserialize(Of t)(s, New t)

            'Dim js As New System.Web.Script.Serialization.JavaScriptSerializer

            'Dim o As t
            'Try
            '    o = js.Deserialize(Of t)(s)
            'Catch ex As Exception
            '    o = New t
            'End Try

            'If o Is Nothing Then
            '    o = New t
            'End If

            'Return o

        End Function
        Public Function GetSetDataJson(value As Object, ByRef json As String) As Object
            json = MyApp.JSONSerialize(value)
            Return value

        End Function


        Public Sub WriteProcLog(l As String, a As MyApp.Task.TaskType)

            Dim logger As NLog.Logger = NLog.LogManager.GetLogger(a.ToString)

            Dim li = New NLog.LogEventInfo With {
                .Level = NLog.LogLevel.Info,
                .Message = l.Replace("(tab)", vbTab),
                .TimeStamp = Date.UtcNow
            }
            logger.Log(li)

            'If LogEnabled Then
            UI.Page.WriteLog(l.Replace("(tab)", "&emsp;"))


        End Sub




        Public Function ToUTF8DB(s As String) As String

            If s = "" Then
                Return ""
            Else
                Dim b = Encoding.UTF8.GetBytes(s)
                For ct = 0 To b.Length - 1
                    If (b(ct) And &HF0) = &HF0 Then
                        ' ( {&HE0,&H0,&H0,&h00})
                        b(ct) = &HE0
                        b(ct + 1) = &H0
                        b(ct + 2) = &H0
                        b(ct + 3) = &H0

                    End If
                Next

                Return Encoding.UTF8.GetString(b)

            End If

        End Function


        Public Function EnumVal(Of tres As {Structure})(s As String) As tres


            Dim val As tres

            [Enum].TryParse(Of tres)(s.ToUpper, val)

            Return val
            'Return [Enum].TryParse(GetType(tres), s, True)

        End Function
        Public Function EnumToDic(Of tres As {Structure})() As Dictionary(Of Integer, String)

            Dim d As New Dictionary(Of Integer, String)
            Dim names = [Enum].GetNames(GetType(tres))
            Dim vals = [Enum].GetValues(GetType(tres))

            For ct = 0 To vals.Length - 1
                d.Add(vals(ct), names(ct))
            Next

            Return d

        End Function

        Public Function GetUser() As mDB.User

            Return GetUser(True)

        End Function
        Public Function GetUser(Redirect As Boolean) As mDB.User

            Dim CacheObjName = "AUTH_USERS"
            Dim CurrUser = Nothing
            If HttpContext.Current IsNot Nothing Then
                CurrUser = HttpContext.Current.Items(CacheObjName)
            End If

            If CurrUser Is Nothing Then

                Dim AU = New MyUI.AuthUsers()

                If AU.IsAuthenticated Then
                    CurrUser = AU.GetUserData
                End If

            End If

            If CurrUser Is Nothing Then
                If Redirect Then
                    HttpContext.Current.Response.Redirect("~/Site/Login.aspx?r=ok", True)
                Else
                    Return Nothing
                End If
            Else
                HttpContext.Current.Items(CacheObjName) = CurrUser
            End If

            Return CurrUser

        End Function

        Public Function GetUserLimitPlan(l As mDB.Plan.LimitType, ui As Boolean, ParamArray p() As Object) As Boolean

            Dim user = GetUser()

            If user.LimitPlan(l, p) Then
                Dim page As MyUI.PageBaseApp = HttpContext.Current.CurrentHandler

                If ui Then
                    page.AddJScript("show_upgrade_plain();")
                End If


                Return True


            Else
                Return False
            End If


        End Function
        'Public Function GetCurrAccount() As mDB.Account

        '    Dim CurrUser = MyApp.GetUser

        '    'Return CurrUser.Tab_Account.GetByPK(Utils.Conv.ToInt(CurrUser.Session(mDB.User.SessionKey.CURR_ACC)))
        '    Return CurrUser.Tab_Account.GetByPK(CurrUser.Session.CurrAccount)


        'End Function
        Public Function GetCurrGroup() As mDB.Group_Account

            Dim CurrUser = MyApp.GetUser

            If CurrUser.Session.ActiveGroup Then
                Return CurrUser.CurrGroup
            Else
                Return CurrUser.CurrGroup

            End If


            ''Dim ids As List(Of Integer) = CurrUser.Session(mDB.User.SessionKey.CURR_ACCS)
            'If CurrUser.Session.CurrAccounts.Count = 0 Then
            '    Return New List(Of mDB.Account) From {GetCurrAccount()}
            'Else
            '    Return CurrUser.Tab_Account.Where("ID", "IN", CurrUser.Session.CurrAccounts).ToList '(Utils.Conv.ToInt(CurrUser.Session(mDB.User.SessionKey.CURR_ACC)))

            'End If



        End Function


        Public Function NetFilter(Of tres)(l As List(Of tres), n() As MyApp.Network.AccType) As List(Of tres)

            'Return (From o As Object In l Where o.Network_Id = n Select sssaa as integer = o ).ToList
            Return l.Where(Function(o As Object) n.Contains(o.Network_Id)).ToList
            'CurrAccount = CurrUser.Tab_Account.GetByPK(Utils.Conv.ToInt(Session("CurrAccountID")))


        End Function


        Public Function AlertAdd(AlertType As mDB.Alert.Type, ToAccountID As Integer, FromAccountID As Integer, AlertDate As Date, AlertData As Object) As mDB.Alert
            Dim db = mDB.GetDB

            'inserisco l'alert
            Dim a = New mDB.Alert With {
                    .Account_Id = ToAccountID,
                    .Alert_Type_Id = AlertType,
                    .From_Account_Id = FromAccountID,
                    .Alert_Date = AlertDate,
                    .Alert_Data = MyApp.JSONSerialize(AlertData)
                }

            db.TAB.Alert.InsertOnSubmit(a)
            db.SubmitChanges()

            'inserisco il riferimento a tutti gli user che lo devono vedere
            Dim Users = db.TAB.User_Account.BY.User_Account.Account_Id(ToAccountID).ToList
            For Each u In Users
                db.TAB.User_Alert.InsertOnSubmit(New mDB.User_Alert With {
                    .Alert_Id = a.Id,
                    .User_Id = u.User_Id
                })
            Next

            db.SubmitChanges()

            Return a



        End Function



        'Public Function AlertAdd(AlertType As mDB.Alert.Type, ToAccountID As Integer, FromAccountID As Integer, AlertDate As Date, AlertData As Object) As mDB.Alert
        '    Dim db = mDB.GetDB

        '    Dim User = db.TAB.User_Account.BY.User_Account.Account_Id(ToAccountID).ToObj

        '    If User IsNot Nothing Then
        '        'Dim CurrUser = MyApp.Session.GetUser
        '        Dim a = New mDB.Alert With {
        '            .User_Id = User.User_Id,
        '            .Alert_Type_Id = AlertType,
        '            .Create_Date = Date.UtcNow, .Alert_Date = AlertDate,
        '            .Account_Id = ToAccountID,
        '            .From_Account_Id = FromAccountID,
        '            .Alert_Data = MyApp.JSONSerialize(AlertData)
        '        }

        '        db.TAB.Alert.InsertOnSubmit(a)

        '        db.SubmitChanges()

        '        Return a

        '    Else

        '        Return Nothing

        '    End If


        'End Function
    End Module

    Public Class Session

        'Public Const GEO_AUTO_AREA_ADD = "GeoAutoAreaAdd"
        'Public Const GEO_SELECT_AREA_TYPE = "GeoSelectAreaType"
        'Public Const GEO_POLYGON_LAYERS = "GeoPolygonLayers"
        'Public Const GEO_AUTO_INFO = "GeoAutoInfo"
        'Public Const GEO_GROUP_AREA_TYPE = "GeoGroupAreaType"
        'Public Const GEO_SECTORY_CATEGORY = "GeoSectoryCategory"
        'Public Const AREA_COMPARE = "AreaCompare"
        Public Enum key
            'MESSAGE_LAST_UPDATE
            QUERY_RT_LAST_UPDATE
        End Enum

        Public Shared Sub SetValue(k As key, o As Object)

            HttpContext.Current.Session(k.ToString) = o

        End Sub

        Public Shared Function GetValue(k As key) As Object

            Return HttpContext.Current.Session(k.ToString)

        End Function
        Public Shared Function GetValue(Of tres)(k As key) As tres

            Return HttpContext.Current.Session(k.ToString)

        End Function

        Public Shared Function GetValueStr(k As key) As String

            Return Utils.GetValue(HttpContext.Current.Session, k.ToString)

        End Function
        Public Shared Function GetValueInt(k As key) As Integer

            Return Utils.GetValueInt(HttpContext.Current.Session, k.ToString)

        End Function
        Public Shared Function GetValueDbl(k As key) As Double

            Return Utils.GetValueDbl(HttpContext.Current.Session, k.ToString)

        End Function
        Public Shared Function GetValueDate(k As key) As Date

            Return Utils.GetValueDate(HttpContext.Current.Session, k.ToString)

        End Function



    End Class


    Namespace Task
        ' solo logica db/dati

        Public Enum TaskType
            ALL = 0
            UPDATE_ACCOUNTS = 1
            UPDATE_QUERY = 2
            SEND_POSTS = 3
            ELABORATE_DATA = 4
            UPDATE_POSTS = 5
            AUTO_FOLLOW = 6
            NET_API = 7
            NET_CONNECT = 8
            INDEX_DATA = 9
            DEBUG = 10
            SCHEDULE = 11
            'REAL_TIME = 7

        End Enum
        Public Enum TaskStatusType

            READY = 0
            RUNNING = 1

        End Enum

        Public Class Update


            Public Shared Sub AccountKlout()
                Const MacAccountsUpdate = 1000
                Dim db As mDB = mDB.GetDB
                Dim kl = New MyApp.Network.Klout

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE KLOUT ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                For Each Acc In Accounts

                    Dim Accs = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        JoinLeft("account_klout", "account_id", "account_link_id").Where("account_klout.account_id is null").
                        Limit(1000).
                    ToList(Of mDB.Account)()


                    If Accs.Count > 0 Then
                        MyApp.WriteProcLog(SF("(tab)begin update klout: {0}, number users: {1}", Acc.ToString, Accs.Count), TaskType.UPDATE_ACCOUNTS)

                        For Each A In Accs

                            Try

                                kl.DownloadAccount(A)

                            Catch ex As WebApi.Net.ExceptionAPI


                            End Try

                        Next

                    End If

                Next

                MyApp.WriteProcLog("END UPDATE KLOUT ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)


            End Sub



            Public Shared Sub AccountAccounts()

                ' aggiorna la anagrafiche degli account collegati agli user
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                AccountAccountsUpdate(Accounts, GloukDB.Account.UpdateAccountMode.ALL)


                MyApp.WriteProcLog("END UPDATE ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub

            Public Shared Sub AccountAccountsUpdate(Accounts As List(Of mDB.Account), mode As mDB.Account.UpdateAccountMode)
                Const MaxAccountUpdate = 2000
                Dim db As mDB = mDB.GetDB

                '----------------------------------
                ' TWITTTER
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, MyApp.Network.NetTypeToAccTypes(WebApi.Type.TWITTER))



                    Dim ids As New List(Of String)
                    'Dim LinkTypes As New List(Of mDB.Account_Link.Type)

                    '----------------------------------------------
                    'user account
                    If Acc.Account_Add_Info.Profile_Update < Date.UtcNow.AddHours(-1) Then
                        ids.Add(Acc.Account_Code)
                    End If

                    If mode = mDB.Account.UpdateAccountMode.ALL Then

                        '---------------------------------------------------------------------
                        'tutti i follower
                        'ids.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Update.
                        '    REL.Account.Account_Link.
                        '    BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                        '    Where("profile_update", "<", Date.UtcNow.AddDays(-2)).
                        '    SetSelect("account.account_code").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of String)("account_code"))

                        'qfoll = db.TAB.Account_Link.BY.Account_Link.Account_Id(Acc.Id, GloukDB.Account_Link.Type.FOLLOWER).
                        '    Where("account_link_id", ">", Acc.Account_Elaboration.Account_Follower_Last_Id).
                        '    OrderBy("account_link_id").
                        'Limit(MaxAccountUpdate + 1)


                        ids.AddRange(
                            db.TAB.Account.
                            REL.Account.Account_Add_Info.
                            Join(Acc.View_Follower_Block("Follower_Account_Last_Id"), "account_link_id", "account.id", "Account_Link", "").
                            Where("profile_update", "<", Date.UtcNow.AddDays(-2)).
                            SetSelect("account.account_code").
                        ToList(Of String)("account_code"))


                        '---------------------------------------------------------------------
                        'tutti i friend
                        'ids.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Update.
                        '    REL.Account.Account_Link.
                        '    BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FRIENDS).
                        '    Where("profile_update", "<", Date.UtcNow.AddDays(-7)).
                        '    SetSelect("account.account_code").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of String)("account_code"))

                        'qfriend = db.TAB.Account_Link.BY.Account_Link.Account_Id(Acc.Id, GloukDB.Account_Link.Type.FRIENDS).
                        '    Where("account_link_id", ">", Acc.Account_Elaboration.Account_Follower_Last_Id).
                        '    OrderBy("account_link_id").
                        'Limit(MaxAccountUpdate + 1)

                        'ids.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Update.
                        '    Join(qfoll, "account_link_id", "account.id", "Account_Link", "").
                        '    Where("profile_update", "<", Date.UtcNow.AddDays(-7)).
                        '    SetSelect("account.account_code").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of String)("account_code"))

                        'trova tutti gli id degli account da condividere i post (task)
                        ids.AddRange(
                            db.TAB.Account.
                            REL.Account.Account_Add_Info.
                            REL.Account.Task_Send.
                            BY.Task_Send.Account_Id(Acc.Id).
                            Where("enabled_task", "=", True).
                            Where("profile_update", "<", Date.UtcNow.AddHours(-1)).
                            SetSelect("account.account_code").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of String)("account_code"))

                    End If

                    Dim Datamin = Acc.GetDateMinUpdate

                    If mode = mDB.Account.UpdateAccountMode.ALL Or mode = mDB.Account.UpdateAccountMode.ENGAGEMENT Then

                        Dim DataExpEngagementAccount = Date.UtcNow.AddDays(-2)
                        If mode = mDB.Account.UpdateAccountMode.ENGAGEMENT Then
                            DataExpEngagementAccount = Date.UtcNow.AddMonths(-1)
                        End If

                        'ricavo la data minore

                        'Accounts collegati ad una menzione
                        ids.AddRange(
                            db.TAB.Account.
                            REL.Account.Account_Add_Info.
                            REL.Account.Message_Post.
                            BY.Message_Post.To_Account_Id(Acc.Id).
                            Where("pubb_date", ">", Datamin.AddDays(-7)).
                            Where("profile_update", "<", DataExpEngagementAccount).
                            SetSelect("account.account_code").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of String)("account_code"))

                        'Accounts collegati ad un messaggio privato INVIATO e RICEVUTO
                        'ids.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Add_Info.
                        '    REL.Account.Private_Post_To_Account.
                        '    BY.Private_Post.Account_Id(Acc.Id, True).
                        '    Where("pubb_date", ">", Datamin.AddDays(-7)).
                        '    Where("profile_update", "<", DataExpEngagementAccount).
                        '    SetSelect("account.account_code").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of String)("account_code"))

                        ids.AddRange(
                            db.TAB.Account.
                            REL.Account.Account_Add_Info.
                            REL.Account.Private_Post_Last_To_Account.
                            BY.Private_Post_Last.Account_Id(Acc.Id, True).
                            Where("pubb_date", ">", Datamin.AddDays(-7)).
                            Where("profile_update", "<", DataExpEngagementAccount).
                            SetSelect("account.account_code").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of String)("account_code"))

                        'ids.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Add_Info.
                        '    REL.Account.Private_Post_To_Account.
                        '    BY.Private_Post.Account_Id(Acc.Id, False).
                        '    Where("pubb_date", ">", Datamin.AddDays(-7)).
                        '    Where("profile_update", "<", DataExpEngagementAccount).
                        '    SetSelect("account.account_code").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of String)("account_code"))

                        ids.AddRange(
                            db.TAB.Account.
                            REL.Account.Account_Add_Info.
                            REL.Account.Private_Post_Last_To_Account.
                            BY.Private_Post_Last.Account_Id(Acc.Id, False).
                            Where("pubb_date", ">", Datamin.AddDays(-7)).
                            Where("profile_update", "<", DataExpEngagementAccount).
                            SetSelect("account.account_code").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of String)("account_code"))


                        'Accounts collegati ad un retweet
                        ' DA CAMBIARE METTERE USARE SOLO SHARE_DETT
                        'ids.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Add_Info.
                        '    REL.Account.Share_Detail.
                        '    REL.Share_Detail.Share_Post.
                        '    BY.Share_Post.Account_Id(Acc.Id).
                        '    Where("share_det_update", ">", Datamin.AddDays(-7)).
                        '    Where("profile_update", "<", DataExpEngagementAccount).
                        '    SetSelect("account.account_code").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of String)("account_code"))

                        ids.AddRange(
                            db.TAB.Account.
                            REL.Account.Account_Add_Info.
                            REL.Account.Share_Detail.
                            BY.Share_Detail.To_Account_Id(Acc.Id).
                            Where("pubb_date", ">", Datamin.AddDays(-7)).
                            Where("profile_update", "<", DataExpEngagementAccount).
                            SetSelect("account.account_code").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of String)("account_code"))

                    End If

                    If mode = mDB.Account.UpdateAccountMode.ALL Or mode = mDB.Account.UpdateAccountMode.AUTO_FOLLOW Then

                        'se non riesce rimette Followed_Update indietro
                        ids.AddRange(Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.PENDING).
                            REL.Auto_Follow_Account.Account.
                            REL.Account.Account_Add_Info.
                            Where("profile_update", "<", Date.UtcNow.AddMonths(-1)).
                            SetSelect("account_code").
                         ToList(Of String)("account_code"))

                    End If

                    If mode = GloukDB.Account.UpdateAccountMode.FRIENDS Then
                        '---------------------------------------------------------------------
                        'tutti i friend
                        ids.AddRange(
                            Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FRIENDS).
                            REL._Account_Link.Account.
                            REL.Account.Account_Add_Info.
                            Where("profile_update", "<", Date.UtcNow.AddDays(-7)).
                            SetSelect("account.account_code").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of String)("account_code"))

                    End If

                    'compatto id
                    ids = ids.Distinct.ToList

                    Dim tw = New MyApp.Network.Twitter(Acc.GetOauth)

                    Dim UpdateAccountRelated = True

                    If ids.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)TWITTER begin update account: {0}, number users: {1}", Acc.ToString, ids.Count), TaskType.UPDATE_ACCOUNTS)

                        Try

                            tw.DownloadAccounts(Nothing, ids)   ' ids.Take(MaxAccountUpdate).ToList

                        Catch ex As WebApi.Net.ExceptionAPI

                            UpdateAccountRelated = False
                            MyApp.WriteProcLog(SF("(tab)(tab)error update account: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                        End Try


                        If UpdateAccountRelated Then
                            If mode = mDB.Account.UpdateAccountMode.ALL Then
                                ' follower block update
                                Acc.SetFieldFollowerBlock("Follower_Account_Last_Id")
                                MyApp.WriteProcLog(SF("(tab)(tab)account update, last foll: {0}", Acc.Account_Update.Follower_Account_Last_Id), TaskType.UPDATE_ACCOUNTS)
                            End If

                            If mode = mDB.Account.UpdateAccountMode.ALL Or mode = mDB.Account.UpdateAccountMode.ENGAGEMENT Then
                                'profilo update
                                If ids.Count <= MaxAccountUpdate Then
                                    'Acc.Account_Update.Profile_Related_Update = Date.UtcNow
                                    Acc.Account_Update.Profile_Related_Update = Datamin
                                End If
                            End If

                            db.SubmitChanges()

                        Else
                            MyApp.WriteProcLog(SF("(tab)(tab)account NOT update"), TaskType.UPDATE_ACCOUNTS)
                        End If

                        MyApp.WriteProcLog(SF("(tab)end update account: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)

                    End If


                Next


                '---------------------------------
                ' FACEBBOK
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, MyApp.Network.NetTypeToAccTypes(WebApi.Type.FACEBOOK))

                    Dim idsAccount As New List(Of String)
                    Dim idsPage As New List(Of String)

                    'page account
                    If Acc.Account_Add_Info.Profile_Update < Date.UtcNow.AddHours(-6) Then
                        If Acc.Network_Id = Network.AccType.FACEBOOK_USER Then
                            idsAccount.Add(Acc.Account_Code)
                        Else
                            idsPage.Add(Acc.Account_Code)
                        End If
                    End If

                    'Accounts collegati ad un messaggio
                    Dim AccMess = db.TAB.Account.
                        REL.Account.Account_Update.
                        REL.Account.Message_Post.
                        BY.Message_Post.To_Account_Id(Acc.Id).
                        Where("profile_update", "<", Date.UtcNow.AddDays(-2)).
                    ToList

                    idsAccount.AddRange(
                        MyApp.NetFilter(AccMess, {Network.AccType.FACEBOOK_USER}).Select(Function(o) o.Account_Code).ToList)
                    idsPage.AddRange(
                        MyApp.NetFilter(AccMess, {Network.AccType.FACEBOOK_PAGE}).Select(Function(o) o.Account_Code).ToList)


                    idsAccount = idsAccount.Distinct.ToList
                    idsPage = idsPage.Distinct.ToList

                    Dim tw = New MyApp.Network.Facebook
                    tw.oauth2 = Acc.GetOauth2


                    Dim UpdateAccountRelated = True

                    'ACCOUNT
                    If idsAccount.Count > 0 Then
                        MyApp.WriteProcLog(SF("(tab)FACEBOOK begin update account: {0}, number users: {1}", Acc.ToString, idsAccount.Count), TaskType.UPDATE_ACCOUNTS)

                        Try

                            tw.DownloadAccounts(idsAccount)

                        Catch ex As WebApi.Net.ExceptionAPI
                            'Catch ex As WebApi.Net.ExceptionRequest

                            'MyApp.WriteProcLog(SF("(tab)(tab)error update account: ExceptionRequest: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                        End Try

                        MyApp.WriteProcLog(SF("(tab)end update account: {0} ", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)
                    End If

                    'PAGE

                    If idsPage.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)FACEBOOK begin update account page: {0}, number users: {1}", Acc.ToString, idsPage.Count), TaskType.UPDATE_ACCOUNTS)

                        Try

                            tw.DownloadAccountsPage(idsPage)

                        Catch ex As WebApi.Net.ExceptionAPI

                            'MyApp.WriteProcLog(SF("(tab)(tab)error update account page: ExceptionRequest: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                        End Try

                        MyApp.WriteProcLog(SF("(tab)end update account page: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)
                    End If

                    If UpdateAccountRelated Then
                        Acc.Account_Update.Profile_Related_Update = Date.UtcNow
                        db.SubmitChanges()

                    End If


                Next

                '---------------------------------
                ' LINKEDIN
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, MyApp.Network.NetTypeToAccTypes(WebApi.Type.LINKEDIN))

                    Dim idsAccount As New List(Of String)
                    Dim idsCompany As New List(Of String)

                    'page account
                    If Acc.Account_Add_Info.Profile_Update < Date.UtcNow.AddHours(-6) Then
                        If Acc.Network_Id = Network.AccType.LINKEDIN_PEOPLE Then
                            idsAccount.Add(Acc.Account_Code)
                        Else
                            idsCompany.Add(Acc.Account_Code)
                        End If
                    End If

                    'Accounts collegati ad un messaggio
                    Dim AccMess = db.TAB.Account.
                        REL.Account.Account_Update.
                        REL.Account.Message_Post.
                        BY.Message_Post.To_Account_Id(Acc.Id).
                        Where("profile_update", "<", Date.UtcNow.AddDays(-2)).
                    ToList

                    idsAccount.AddRange(
                        MyApp.NetFilter(AccMess, {Network.AccType.LINKEDIN_PEOPLE}).Select(Function(o) o.Account_Code).ToList)
                    idsCompany.AddRange(
                        MyApp.NetFilter(AccMess, {Network.AccType.LINKEDIN_COMPANY}).Select(Function(o) o.Account_Code).ToList)


                    idsAccount = idsAccount.Distinct.ToList
                    idsCompany = idsCompany.Distinct.ToList

                    Dim lk = New MyApp.Network.Linkedin
                    lk.oauth2 = Acc.GetOauth2


                    Dim UpdateAccountRelated = True

                    'ACCOUNT
                    If idsAccount.Count > 0 Then
                        MyApp.WriteProcLog(SF("(tab)LINKEDIN begin update account: {0}, number users: {1}", Acc.ToString, idsAccount.Count), TaskType.UPDATE_ACCOUNTS)

                        Try

                            lk.DownloadAccountsPeople(idsAccount)

                        Catch ex As WebApi.Net.ExceptionAPI

                            'MyApp.WriteProcLog(SF("(tab)(tab)error update account: ExceptionRequest: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                        End Try

                        MyApp.WriteProcLog(SF("(tab)end update account: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)
                    End If

                    'COMPANY
                    If idsCompany.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)LINKEDIN begin update account page: {0}, number users: {1}", Acc.ToString, idsCompany.Count), TaskType.UPDATE_ACCOUNTS)

                        Try

                            lk.DownloadAccountsCompanies(idsCompany)

                        Catch ex As WebApi.Net.ExceptionAPI

                            ' MyApp.WriteProcLog(SF("(tab)(tab)error update account page: ExceptionRequest: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                        End Try

                        MyApp.WriteProcLog(SF("(tab)end update account page: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)
                    End If

                    If UpdateAccountRelated Then
                        Acc.Account_Update.Profile_Related_Update = Date.UtcNow
                        db.SubmitChanges()

                    End If


                Next

            End Sub


            'Public Shared Sub AccountPosts_old()
            '    ' scarica i post degli account collegati agli user
            '    Dim db As mDB = mDB.GetDB
            '    Dim ThreadException As Exception = Nothing

            '    Dim Accounts = db.VIEW.Account_UserEnabled.
            '    ToList()

            '    MyApp.WriteProcLog("BEGIN UPDATE POST", AutoProcType.UPDATE_POSTS)

            '    '---------------------------------
            '    ' TWITTTER
            '    '---------------------------------
            '    For Each Acc In App.NetFilter(Accounts, {NetAccType.TWITTER_ACCOUNT})

            '        Dim accs As New List(Of mDB.Account)

            '        'user account
            '        'If Acc.Account_Update.Post_Update_Date < Date.UtcNow.AddDays(-0.5) And Acc.Account_Update.Post_Update_Count < Acc.Account_Update.Post_Count Then
            '        If Acc.Account_Update.Post_Update_Count <> Acc.Account_Update.Post_Count Then
            '            accs.Add(Acc)
            '        Else
            '            'IMPORTANTE la data di aggiornamento dei post è sempre almeno la data di aggiornamento del profilo
            '            Acc.Account_Update.Post_Update_Date = Acc.Account_Update.Profile_Update
            '            db.SubmitChanges()
            '        End If

            '        'trova tutti gli acount da condifivere i post
            '        accs.AddRange(
            '            db.TAB.Account.
            '            REL.Account.Account_Update.
            '            REL.Account.Task_Send.
            '            BY.Task_Send.Account_Id(Acc.Id).
            '            Where("post_update_count <> post_count").
            '            Where("post_update_date", "<", Date.UtcNow.AddHours(-1)).
            '        ToList)

            '        'trova tutti gli followers da agiornare i post
            '        accs.AddRange(
            '            db.TAB.Account.
            '            REL.Account.Account_Update.
            '            REL.Account.Account_Link.
            '            BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
            '            Where("post_update_count <> post_count").
            '            Where("post_update_date", "<", Date.UtcNow.AddDays(-3)).
            '        ToList)

            '        If accs.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)TWITTER begin update post : {0}, number users: {1}", Acc.ToString, accs.Count), AutoProcType.UPDATE_POSTS)
            '            HttpContext.Current.Items("ex_post") = Nothing

            '            Dim Threads = New Utils.Threading.ThreadsManage(4)

            '            For Each A In accs

            '                Dim tw = New App.Network.Twitter
            '                ' passa il context corrente lo uso come ponte
            '                tw.HttpContextCurrent = HttpContext.Current

            '                Threads.Start(AddressOf tw.DownloadAccountPostsAsync, A.Id)
            '                'tw.DownloadAccountPostsAsync(A.Id)

            '                If GetAsyncException("Exception_UpdateUserPosts") IsNot Nothing Then
            '                    Exit For
            '                End If

            '            Next

            '            Threads.WaitEnd()

            '            'se esiste una eccezione verifica se è perchè non ci sono + account per scaricare
            '            ThreadException = GetAsyncException("Exception_UpdateUserPosts")
            '            If ThreadException IsNot Nothing Then
            '                If ThreadException.GetType <> GetType(WebApi.Net.ExceptionTooManyRequestsAllAccount) Then
            '                    Throw ThreadException
            '                End If
            '            End If

            '            MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), AutoProcType.UPDATE_POSTS)

            '        End If

            '    Next

            '    '---------------------------------
            '    ' FACEBOOK
            '    '---------------------------------
            '    For Each Acc In App.NetFilter(Accounts, {NetAccType.FACEBOOK_PAGE})

            '        Dim accs As New List(Of mDB.Account)

            '        If Acc.Account_Update.Post_Update_Date < Date.UtcNow.AddHours(-1) Then
            '            accs.Add(Acc)
            '        End If

            '        If accs.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)FACEBOOK begin update post : {0}, number users: {1}", Acc.ToString, accs.Count), AutoProcType.UPDATE_POSTS)

            '            Dim fb = New App.Network.Facebook

            '            For Each a In accs

            '                fb.oauth2 = Acc.getOauth2

            '                Try

            '                    fb.DownloadAccountPosts(a)

            '                Catch ex As WebApi.Net.ExceptionServiceBase

            '                    'MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

            '                End Try

            '            Next

            '            MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), AutoProcType.UPDATE_POSTS)

            '        End If

            '    Next

            '    '---------------------------------
            '    ' LINKEDIN
            '    '---------------------------------
            '    For Each Acc In App.NetFilter(Accounts, {NetAccType.LINKEDIN_COMPANY})

            '        Dim accs As New List(Of mDB.Account)

            '        If Acc.Account_Update.Post_Update_Date < Date.UtcNow.AddHours(-1) Then
            '            accs.Add(Acc)
            '        End If

            '        If accs.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)LINKEDIN begin update post : {0}, number users: {1}", Acc.ToString, accs.Count), AutoProcType.UPDATE_POSTS)

            '            Dim lk = New App.Network.Linkedin

            '            For Each a In accs

            '                lk.oauth2 = Acc.getOauth2

            '                Try

            '                    lk.DownloadAccountPosts(a)

            '                Catch ex As WebApi.Net.ExceptionServiceBase

            '                    'MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

            '                End Try

            '            Next

            '            MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), AutoProcType.UPDATE_POSTS)

            '        End If

            '    Next

            '    MyApp.WriteProcLog("END UPDATE POST", AutoProcType.UPDATE_POSTS)
            '    MyApp.WriteProcLog("----------------------------------------------------------", AutoProcType.UPDATE_POSTS)

            'End Sub
            Public Shared Sub AccountPosts()
                Const MaxAccountUpdate = 1000
                ' scarica i post degli account collegati agli user
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE POST", TaskType.UPDATE_POSTS)


                '---------------------------------
                ' TWITTTER
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.TWITTER_ACCOUNT})

                    Dim AccIds As New List(Of Integer)

                    'user account
                    If Acc.Account_Add_Info.Post_Update_Count <> Acc.Account_Add_Info.Post_Count Then
                        AccIds.Add(Acc.Id)
                    Else
                        'IMPORTANTE la data di aggiornamento dei post è sempre almeno la data di aggiornamento del profilo
                        Acc.Account_Add_Info.Post_Update = Acc.Account_Add_Info.Profile_Update
                        db.SubmitChanges()
                    End If

                    'trova tutti gli acount da condifivere i post
                    'AccIds.AddRange(
                    '    db.TAB.Account.
                    '    REL.Account.Account_Update.
                    '    REL.Account.Task_Send.
                    '    BY.Task_Send.Account_Id(Acc.Id).
                    '    Where("post_update_count <> post_count").
                    '    Where("post_update", "<", Date.UtcNow.AddHours(-1)).
                    '    SetSelect("account.id").
                    '    Limit(MaxAccountUpdate + 1).
                    'ToList(Of Integer)("id"))

                    AccIds.AddRange(
                        Acc.Tab_Task_Send.
                        REL.Task_Send.Account_Add_Info_Share.
                        Where("post_update_count <> post_count").
                        Where("post_update", "<", Date.UtcNow.AddHours(-1)).
                        SetSelect("account_add_info.account_id").
                        Limit(MaxAccountUpdate + 1).
                    ToList(Of Integer)("account_id"))

                    If Acc.Account_Auth.Analysis_Followers Then

                        'trova tutti gli followers da agiornare i post
                        AccIds.AddRange(
                            Acc._Tab_Account_Link_Analysis(True).
                            REL._Account_Link.Account_Add_Info.
                            Where("post_update_count <> post_count").
                            Where("post_update", "<", Date.UtcNow.AddDays(-3)).
                            SetSelect("account_add_info.account_id").
                            Limit(MaxAccountUpdate + 1).
                        ToList(Of Integer)("account_id"))


                        'AccIds.AddRange(
                        '    db.TAB.Account.
                        '    REL.Account.Account_Update.
                        '    REL.Account.Account_Link.
                        '    BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                        '    Where("post_update_count <> post_count").
                        '    Where("post_update", "<", Date.UtcNow.AddDays(-3)).
                        '    SetSelect("account.id").
                        '    Limit(MaxAccountUpdate + 1).
                        'ToList(Of Integer)("id"))

                    End If


                    AccIds = AccIds.Distinct.Take(MaxAccountUpdate).ToList

                    If AccIds.Count > 0 Then
                        MyApp.WriteProcLog(SF("(tab)TWITTER begin update post : {0}, number users: {1}", Acc.ToString, AccIds.Count), TaskType.UPDATE_POSTS)
                        AccountPostsUpdate(AccIds, mDB.Account.UpdatePostMode.FOLLOWER)
                        MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.ToString), TaskType.UPDATE_POSTS)
                    End If

                Next

                '---------------------------------
                ' FACEBOOK
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.FACEBOOK_PAGE})

                    Dim AccIds As New List(Of Integer)

                    If Acc.Account_Add_Info.Post_Update < Date.UtcNow.AddHours(-1) Then
                        AccIds.Add(Acc.Id)
                    End If

                    AccIds = AccIds.Distinct.Take(MaxAccountUpdate).ToList

                    If AccIds.Count > 0 Then
                        MyApp.WriteProcLog(SF("(tab)FACEBOOK begin update post : {0}, number users: {1}", Acc.ToString, AccIds.Count), TaskType.UPDATE_POSTS)
                        AccountPostsUpdate(AccIds, mDB.Account.UpdatePostMode.FOLLOWER)
                        MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), TaskType.UPDATE_POSTS)

                    End If

                Next

                '---------------------------------
                ' LINKEDIN
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.LINKEDIN_COMPANY})

                    Dim AccIds As New List(Of Integer)

                    If Acc.Account_Add_Info.Post_Update < Date.UtcNow.AddHours(-1) Then
                        AccIds.Add(Acc.Id)
                    End If

                    AccIds = AccIds.Distinct.Take(MaxAccountUpdate).ToList

                    If AccIds.Count > 0 Then
                        MyApp.WriteProcLog(SF("(tab)LINKEDIN begin update post : {0}, number users: {1}", Acc.ToString, AccIds.Count), TaskType.UPDATE_POSTS)
                        AccountPostsUpdate(AccIds, mDB.Account.UpdatePostMode.FOLLOWER)
                        MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), TaskType.UPDATE_POSTS)
                    End If

                Next


                MyApp.WriteProcLog("END UPDATE POST", TaskType.UPDATE_POSTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_POSTS)

            End Sub
            Public Shared Sub ProfilePosts()
                ' scarica i post delle query
                Dim db As mDB = mDB.GetDB
                Dim ThreadException As Exception = Nothing

                Dim Users = db.TAB.User.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE PROFILE USER ACCOUNT", TaskType.UPDATE_QUERY)

                For Each U In Users

                    Dim Profiles As New List(Of mDB.Profile)

                    'profili non scaricati
                    Profiles.AddRange(
                        U.Tab_Profile.
                        Where("post_download_count", "=", -1).
                        SetSelect("profile.*").
                    ToList)

                    Dim AccIds = Profiles.Select(Function(o) o.Account_Id).Distinct.ToList

                    If AccIds.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update profile : {0}, number prof: {1}", U.ToString, AccIds.Count), TaskType.UPDATE_QUERY)

                        AccountPostsUpdate(AccIds, mDB.Account.UpdatePostMode.PROFILE)

                        MyApp.WriteProcLog(SF("(tab)end update query: {0}", U.Name), TaskType.UPDATE_QUERY)

                    End If

                    For Each Prof In Profiles

                        'verifica se tutti sono stati scaricati
                        If Prof.Account.Account_Add_Info.Post_Update > Date.UtcNow.AddHours(-1) Then
                            MyApp.WriteProcLog(SF("(tab)(tab)indicizza profile post: '{0}'", Prof.Account.ToString), TaskType.UPDATE_QUERY)
                            Task.Elaborate.CreateIndexProfilePosts(Prof.Id)
                        End If

                    Next

                    'crea indice e aggiorna profilo

                    '    ' IMPOERTANTE lo metto qui perchè qui sono sicuro che posso indicizzare che ha finito di scaricare tutti i post
                    '    MyApp.WriteProcLog(SF("(tab)(tab)indicizza profile post: '{0}'", Acc.ToString), AutoProcType.UPDATE_QUERY)
                    '    Data.Elaborate.CreateIndexProfilePosts(Prof.Id)


                Next




                MyApp.WriteProcLog("END UPDATE PROFILE USER ACCOUNT", TaskType.UPDATE_QUERY)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_QUERY)
            End Sub

            Public Shared Sub AccountPostsUpdate(AccIds As List(Of Integer), Mode As mDB.Account.UpdatePostMode)
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.TAB.Account.
                    Where("id", "IN", AccIds).
                ToList()

                '---------------------------------
                ' TWITTTER
                '---------------------------------
                Dim ThreadException As Exception = Nothing
                Dim Threads = New Utils.Threading.ThreadsManage(2)

                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.TWITTER_ACCOUNT})

                    HttpContext.Current.Items("ex_post") = Nothing

                    Dim tw = New MyApp.Network.Twitter
                    ' passa il context corrente lo uso come ponte
                    tw.HttpContextCurrent = HttpContext.Current

                    Threads.Start(AddressOf tw.DownloadAccountPostsAsync, New With {.ID = Acc.Id, .Mode = Mode})
                    'tw.DownloadAccountPostsAsync(A.Id)

                    If GetAsyncException("Exception_UpdateUserPosts") IsNot Nothing Then
                        Exit For
                    End If

                Next

                Threads.WaitEnd()

                'se esiste una eccezione verifica se è perchè non ci sono + account per scaricare
                ThreadException = GetAsyncException("Exception_UpdateUserPosts")
                If ThreadException IsNot Nothing Then
                    If ThreadException.GetType <> GetType(WebApi.Net.ExceptionTooManyRequestsAllAccount) Then
                        Throw ThreadException
                    End If
                End If

                '---------------------------------
                ' FACEBOOK
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.FACEBOOK_PAGE})

                    Dim fb = New MyApp.Network.Facebook
                    fb.oauth2 = Acc.GetOauth2

                    Try

                        fb.DownloadAccountPosts(Acc)

                    Catch ex As WebApi.Net.ExceptionAPI

                        'MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                    End Try


                Next

                '---------------------------------
                ' LINKEDIN
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.LINKEDIN_COMPANY})

                    Dim lk = New MyApp.Network.Linkedin

                    lk.oauth2 = Acc.GetOauth2

                    Try

                        lk.DownloadAccountPosts(Acc)

                    Catch ex As WebApi.Net.ExceptionAPI

                        'MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                    End Try


                Next


            End Sub


            'Public Shared Sub AccountPosts2()
            '    ' scarica i post degli account collegati agli user
            '    Dim db As mDB = mDB.GetDB
            '    Dim ThreadException As Exception = Nothing

            '    Dim Accounts = db.VIEW.Account_UserEnabled.
            '    ToList()

            '    MyApp.WriteProcLog("BEGIN UPDATE POST", AutoProcType.UPDATE_POSTS)

            '    '---------------------------------
            '    ' TWITTTER
            '    '---------------------------------
            '    For Each Acc In App.NetFilter(Accounts, {NetAccType.TWITTER_ACCOUNT})

            '        Dim accs As New List(Of mDB.Account)

            '        'user account
            '        'If Acc.Account_Update.Post_Update < Date.UtcNow.AddDays(-0.5) And Acc.Account_Update.Post_Update_Count < Acc.Account_Update.Post_Count Then
            '        If Acc.Account_Update.Post_Update_Count <> Acc.Account_Update.Post_Count Then
            '            accs.Add(Acc)
            '        Else
            '            'IMPORTANTE la data di aggiornamento dei post è sempre almeno la data di aggiornamento del profilo
            '            Acc.Account_Update.Post_Update = Acc.Account_Update.Profile_Update
            '            db.SubmitChanges()
            '        End If

            '        'trova tutti gli acount da condifivere i post
            '        accs.AddRange(
            '            db.TAB.Account.
            '            REL.Account.Account_Update.
            '            REL.Account.Task_Send.
            '            BY.Task_Send.Account_Id(Acc.Id).
            '            Where("post_update_count <> post_count").
            '            Where("post_Update", "<", Date.UtcNow.AddHours(-1)).
            '        ToList)

            '        'trova tutti gli followers da agiornare i post
            '        accs.AddRange(
            '            db.TAB.Account.
            '            REL.Account.Account_Update.
            '            REL.Account.Account_Link.
            '            BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
            '            Where("post_update_count <> post_count").
            '            Where("post_Update", "<", Date.UtcNow.AddDays(-3)).
            '        ToList)

            '        If accs.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)TWITTER begin update post : {0}, number users: {1}", Acc.Fullname, accs.Count), AutoProcType.UPDATE_POSTS)
            '            HttpContext.Current.Items("ex_post") = Nothing

            '            Dim Threads = New Utils.Threading.ThreadsManage(4)

            '            For Each A In accs

            '                Dim tw = New App.Network.Twitter
            '                ' passa il context corrente lo uso come ponte
            '                tw.HttpContextCurrent = HttpContext.Current

            '                Threads.Start(AddressOf tw.DownloadAccountPostsAsync, A.Id)
            '                'tw.DownloadAccountPostsAsync(A.Id)

            '                If GetAsyncException("Exception_UpdateUserPosts") IsNot Nothing Then
            '                    Exit For
            '                End If

            '            Next

            '            Threads.WaitEnd()

            '            'se esiste una eccezione verifica se è perchè non ci sono + account per scaricare
            '            ThreadException = GetAsyncException("Exception_UpdateUserPosts")
            '            If ThreadException IsNot Nothing Then
            '                If ThreadException.GetType <> GetType(WebApi.Net.ExceptionTooManyRequestsAllAccount) Then
            '                    Throw ThreadException
            '                End If
            '            End If

            '            MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), AutoProcType.UPDATE_POSTS)

            '        End If

            '    Next

            '    '---------------------------------
            '    ' FACEBOOK
            '    '---------------------------------
            '    For Each Acc In App.NetFilter(Accounts, {NetAccType.FACEBOOK_PAGE})

            '        Dim accs As New List(Of mDB.Account)

            '        If Acc.Account_Update.Post_Update < Date.UtcNow.AddHours(-1) Then
            '            accs.Add(Acc)
            '        End If

            '        If accs.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)FACEBOOK begin update post : {0}, number users: {1}", Acc.Fullname, accs.Count), AutoProcType.UPDATE_POSTS)

            '            Dim fb = New App.Network.Facebook

            '            For Each a In accs

            '                fb.oauth2 = Acc.getOauth2

            '                Try

            '                    fb.DownloadAccountPosts(a)

            '                Catch ex As WebApi.Net.ExceptionServiceBase

            '                    'MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

            '                End Try

            '            Next

            '            MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), AutoProcType.UPDATE_POSTS)

            '        End If

            '    Next

            '    '---------------------------------
            '    ' LINKEDIN
            '    '---------------------------------
            '    For Each Acc In App.NetFilter(Accounts, {NetAccType.LINKEDIN_COMPANY})

            '        Dim accs As New List(Of mDB.Account)

            '        If Acc.Account_Update.Post_Update < Date.UtcNow.AddHours(-1) Then
            '            accs.Add(Acc)
            '        End If

            '        If accs.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)LINKEDIN begin update post : {0}, number users: {1}", Acc.Fullname, accs.Count), AutoProcType.UPDATE_POSTS)

            '            Dim lk = New App.Network.Linkedin

            '            For Each a In accs

            '                lk.oauth2 = Acc.getOauth2

            '                Try

            '                    lk.DownloadAccountPosts(a)

            '                Catch ex As WebApi.Net.ExceptionServiceBase

            '                    'MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

            '                End Try

            '            Next

            '            MyApp.WriteProcLog(SF("(tab)end update  post: {0}", Acc.Fullname), AutoProcType.UPDATE_POSTS)

            '        End If

            '    Next

            '    MyApp.WriteProcLog("END UPDATE POST", AutoProcType.UPDATE_POSTS)
            '    MyApp.WriteProcLog("----------------------------------------------------------", AutoProcType.UPDATE_POSTS)

            'End Sub
            Public Shared Sub AccountMessagePosts()
                ' scarica i messaggi(post) indirizzati agli account collegati agli user
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog("BEGIN UPDATE MESSAGE POST USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                'trova tutti gli account da agiornare i post
                Dim accs = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                    Where("message_post_update", "<", Date.UtcNow.AddHours(-1)).
                ToList()

                If accs.Count > 0 Then

                    '------------------------------------
                    ' TWITTER
                    '------------------------------------

                    Dim tw = New MyApp.Network.Twitter

                    For Each Acc In MyApp.NetFilter(accs, {Network.AccType.TWITTER_ACCOUNT})

                        tw.oauth = Acc.GetOauth

                        Try

                            tw.DownloadAccountMessagePosts(Acc)

                        Catch ex As WebApi.Net.ExceptionAPI

                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                        End Try

                    Next

                    '------------------------------------
                    ' FACEBOOK
                    '------------------------------------
                    'Dim fb = New App.Network.Facebook

                    'For Each Acc In App.NetFilter(accs, {NetworkType.FACEBOOK_PAGE})

                    '    fb.oauth2 = Acc.getOauth2

                    '    Try

                    '        fb.DownloadAccountMessages(Acc)

                    '    Catch ex As WebApi.Net.ExceptionTooManyRequests

                    '        MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                    '    End Try

                    'Next

                    ''------------------------------------
                    '' LINKEDIN
                    ''------------------------------------
                    'Dim lk = New App.Network.Linkedin

                    'For Each Acc In App.NetFilter(accs, {NetworkType.LINKEDIN_COMPANY})

                    '    lk.oauth2 = Acc.getOauth2

                    '    Try

                    '        lk.DownloadAccountMessages(Acc)

                    '    Catch ex As WebApi.Net.ExceptionTooManyRequests

                    '        MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update message: ExceptionAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_ACCOUNTS)

                    '    End Try

                    'Next




                End If


                MyApp.WriteProcLog("END UPDATE MESSAGE POST USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub

            Public Shared Sub AccountFavoritePosts()
                ' scarica i favoriti(post) indirizzati agli account collegati agli user
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog("BEGIN UPDATE FAVORITE POST USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                'trova tutti gli account da agiornare i post
                Dim accs = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                    Where("favorite_post_update", "<", Date.UtcNow.AddHours(-12)).
                ToList()

                If accs.Count > 0 Then

                    '------------------------------------
                    ' TWITTER
                    '------------------------------------

                    Dim tw = New MyApp.Network.Twitter

                    For Each Acc In MyApp.NetFilter(accs, {Network.AccType.TWITTER_ACCOUNT})

                        tw.oauth = Acc.GetOauth

                        Try

                            tw.DownloadAccountFavoritePosts(Acc)

                        Catch ex As WebApi.Net.ExceptionAPI

                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update favorite: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                        End Try

                    Next

                End If


                MyApp.WriteProcLog("END UPDATE FAVORITE POST USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub

            Public Shared Sub AccountList()
                ' scarica le liste degli account
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog("BEGIN UPDATE LIST ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                'trova tutti gli account da agiornare i post
                Dim accs = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                ToList()

                '                    Where("favorite_post_update", "<", Date.UtcNow.AddHours(-12)).

                If accs.Count > 0 Then

                    '------------------------------------
                    ' TWITTER
                    '------------------------------------

                    Dim tw = New MyApp.Network.Twitter

                    For Each Acc In MyApp.NetFilter(accs, {Network.AccType.TWITTER_ACCOUNT})

                        tw.oauth = Acc.GetOauth

                        Try

                            tw.DownloadAccountLists(Acc)

                        Catch ex As WebApi.Net.ExceptionAPI

                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update favorite: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                        End Try

                    Next

                End If


                MyApp.WriteProcLog("END UPDATE LIST ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub


            Public Shared Sub AccountMessagesConversations()
                Dim db As mDB = mDB.GetDB
                Dim tw = New MyApp.Network.Twitter

                MyApp.WriteProcLog("BEGIN UPDATE MESSAGE CONV", TaskType.UPDATE_ACCOUNTS)


                'Dim acc = New mDB.Account With {.Id = 0}

                Dim conv As List(Of mDB.Message_Post)
                Do

                    'controllo se ci sono tutti i riferimenti alle conversazioni
                    'conv = db.TAB.Message_Post.
                    '    JoinLeft("message_post", "post_code", "message_post.reply_to_post_code", "mess", "").
                    '    Where("mess.id is null").
                    '    Where("message_post.reply_to_post_code", "<>", "").
                    '    Where("message_post.Parent_Post_Update", "=", False).
                    '    SetSelect("message_post.*").
                    '    ToList()

                    conv = db.TAB.Message_Post.
                        Where("message_post.Parent_Post_Update", "=", True).
                        SetSelect("message_post.*").
                        ToList()


                    MyApp.WriteProcLog(SF("(tab)conv to donwload: {0}", conv.Count), TaskType.UPDATE_ACCOUNTS)

                    Try

                        For Each c In conv

                            tw.DownloadConversationMessage(c)

                        Next

                    Catch ex As WebApi.Net.ExceptionTooManyRequestsAllAccount

                        MyApp.WriteProcLog(SF("(tab)(tab)error update share details : ExceptionTooManyRequestsAllAccount"), TaskType.UPDATE_ACCOUNTS)
                        Exit Do

                    End Try

                Loop Until conv.Count = 0

                MyApp.WriteProcLog("END UPDATE MESSAGE CONV", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub

            Public Shared Sub AccountPrivatePosts()
                ' scarica i messaggi privati(post) indirizzati agli account collegati agli user
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog("BEGIN UPDATE PRIVATE POST USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                'trova tutti gli account da agiornare i post
                Dim accs = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                    Where("private_post_update", "<", Date.UtcNow.AddHours(-1)).
                ToList()

                If accs.Count > 0 Then

                    '------------------------------------
                    ' TWITTER
                    '------------------------------------


                    For Each Acc In MyApp.NetFilter(accs, {Network.AccType.TWITTER_ACCOUNT})

                        Dim tw = New MyApp.Network.Twitter(Acc.GetOauth)

                        Try

                            tw.DownloadAccountPrivatePosts(Acc)

                        Catch ex As WebApi.Net.ExceptionAPI

                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update private post: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                        End Try

                    Next

                End If


                MyApp.WriteProcLog("END UPDATE PRIVATE POST USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub
            Public Shared Sub AccountShares()
                ' scarica i post che condividono post(retweet) di account collegati agli user
                Dim db As mDB = mDB.GetDB
                Dim tw = New MyApp.Network.Twitter

                MyApp.WriteProcLog("BEGIN UPDATE SHARE USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                'trova tutti gli account da agiornare i post
                Dim accs = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                    Where("share_update", "<", Date.UtcNow.AddDays(-0.5)).
                ToList()

                If accs.Count > 0 Then

                    For Each Acc In accs

                        tw.oauth = Acc.GetOauth

                        Try

                            tw.DownloadAccountShares(Acc)

                        Catch ex As WebApi.Net.ExceptionAPI

                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update share : ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                        End Try

                    Next

                End If

                MyApp.WriteProcLog("END UPDATE SHARE USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub
            Public Shared Sub AccountShareDetails()
                ' scarica le confivisioni fatte su post di account collegati agli user
                Dim db As mDB = mDB.GetDB
                Dim tw = New MyApp.Network.Twitter

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE SHARE DETAILS USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)


                For Each Acc In Accounts

                    'Dim post = db.TAB.Share_Post.
                    '    BY.Share_Post.Account_Id(Acc.Id).
                    '    Where("share_det_update_count <> share_det_count").
                    '    Where("share_det_update", "<", Date.UtcNow.AddDays(-0.5)).
                    'ToList()

                    Dim post = db.TAB.Share_Post.
                        BY.Share_Post.Account_Id(Acc.Id).
                        Where("share_det_update", "=", True).
                    ToList()

                    Dim UpdateShareDet = True
                    If post.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update share details : {0}, number share post: {1}", Acc.ToString, post.Count), TaskType.UPDATE_ACCOUNTS)

                        Try

                            For Each p In post

                                tw.DownloadSharePostDetails(p)

                            Next

                            'IMPORTANTE se vengono scaricati dei post shared rimette la data di aggiornamento dei profili connessi, inferiore alla data del post + vecchio  in modo che i trend vengano creati solo quando tutti gli accorunt sono stati scaricati
                            'Acc.Account_Update.Profile_Related_Update = post.Min(Of Date)(Function(o) o.Pubb_Date).AddDays(-7) '    Date.MinValue
                            'db.SubmitChanges()

                        Catch ex As WebApi.Net.ExceptionTooManyRequestsAllAccount

                            MyApp.WriteProcLog(SF("(tab)(tab)error update share details : ExceptionTooManyRequestsAllAccount"), TaskType.UPDATE_ACCOUNTS)
                            UpdateShareDet = False

                        End Try

                    End If

                    If UpdateShareDet Then
                        Acc.Account_Update.Share_Det_Update = Acc.Account_Update.Share_Update
                        db.SubmitChanges()

                    End If

                Next


                MyApp.WriteProcLog("END UPDATE SHARE DETAILS USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)

            End Sub

            Public Shared Sub AccountFollowers()
                ' aggiorna i collegamenti ai followers degli account collegati agli user
                Dim db As mDB = mDB.GetDB

                'tutti gli account collegati con gli utenti
                'verifica che il conteggio dell'ultimo aggionamento sia diverso e che l'ultimo update abbia + di 24 ore
                Dim Accounts = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                    REL.Account.Account_Add_Info.
                    Where("follower_update_count <> follower_count").
                    Where("follower_update", "<", Date.UtcNow.AddHours(-8)).
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE FOLLOWERS", TaskType.UPDATE_ACCOUNTS)

                '---------------------------------
                ' TWITTTER
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.TWITTER_ACCOUNT})

                    Dim tw = New MyApp.Network.Twitter
                    tw.oauth = Acc.GetOauth

                    MyApp.WriteProcLog(SF("(tab)TWITTER begin update followers: {0}", Acc.ToString), TaskType.UPDATE_ACCOUNTS)

                    Try

                        If tw.DownloadAccountFollowers(Acc) Then

                            Acc.SetAccountLinkStatusFollower()

                        End If

                    Catch ex As WebApi.Net.ExceptionAPI

                        MyApp.WriteProcLog(SF("(tab)(tab)error update follower: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                    End Try

                    'MyApp.WriteProcLog(SF("(tab)TWITTER end update followers: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)

                Next

                '---------------------------------
                ' LINKEDIN
                '---------------------------------
                For Each Acc In MyApp.NetFilter(Accounts, {Network.AccType.LINKEDIN_PEOPLE})

                    Dim lk = New MyApp.Network.Linkedin
                    lk.oauth2 = Acc.GetOauth2


                    MyApp.WriteProcLog(SF("(tab)LINKEDIN begin update followers: {0}", Acc.ToString), TaskType.UPDATE_ACCOUNTS)

                    Try

                        lk.DownloadAccountFollowers(Acc)

                    Catch ex As WebApi.Net.ExceptionAPI

                        MyApp.WriteProcLog(SF("(tab)(tab)error update follower: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                    End Try

                    MyApp.WriteProcLog(SF("(tab)LINKEDIN end update followers: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)

                Next

                MyApp.WriteProcLog("END UPDATE FOLLOWERS", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)


            End Sub
            Public Shared Sub AccountFriends()
                Dim db As mDB = mDB.GetDB

                'tutti gli account collegati con gli utenti
                'verifica che il conteggio dell'ultimo aggionamento sia diverso e che l'ultimo update abbia + di 24 ore
                Dim Accounts = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.REL.Account.Account_Add_Info.
                    Where("friend_update_count <> friend_count").
                    Where("friend_update", "<", Date.UtcNow.AddDays(-0.5)).
                ToList()

                '                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).

                MyApp.WriteProcLog("BEGIN UPDATE FRIENDS", TaskType.UPDATE_ACCOUNTS)

                For Each Acc In MyApp.NetFilter(Accounts, MyApp.Network.NetTypeToAccTypes(WebApi.Type.TWITTER))

                    Dim tw = New MyApp.Network.Twitter
                    tw.oauth = Acc.GetOauth '   userAcc.getOauth

                    MyApp.WriteProcLog(SF("(tab)begin update friends: {0}", Acc.ToString), TaskType.UPDATE_ACCOUNTS)

                    Try

                        If tw.DownloadAccountFriends(Acc) Then

                            Acc.SetAccountLinkStatusFriend()

                        End If

                    Catch ex As WebApi.Net.ExceptionAPI

                        MyApp.WriteProcLog(SF("(tab)(tab)error update friends: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                    End Try

                    'MyApp.WriteProcLog(SF("(tab)end update friends: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)

                    'quando vengono aggionati i follower verifica gli AUTO follow
                    'App.Data.Elaborate.CheckFriendToFollower()


                Next

                For Each Acc In MyApp.NetFilter(Accounts, MyApp.Network.NetTypeToAccTypes(WebApi.Type.GOOGLE))

                    Dim tw = New MyApp.Network.Google(Acc.GetOauth2)

                    MyApp.WriteProcLog(SF("(tab)begin update friends: {0}", Acc.ToString), TaskType.UPDATE_ACCOUNTS)

                    Try

                        If tw.DownloadAccountFriends(Acc) Then

                            Acc.SetAccountLinkStatusFriend()

                        End If

                    Catch ex As WebApi.Net.ExceptionAPI

                        MyApp.WriteProcLog(SF("(tab)(tab)error update friends: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), TaskType.UPDATE_ACCOUNTS)

                    End Try

                    'MyApp.WriteProcLog(SF("(tab)end update friends: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)

                    'quando vengono aggionati i follower verifica gli AUTO follow
                    'App.Data.Elaborate.CheckFriendToFollower()


                Next

                MyApp.WriteProcLog("END UPDATE FRIENDS", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)


            End Sub

            'Public Shared Sub QueryPosts()
            '    ' scarica i post delle query
            '    Dim db As mDB = mDB.GetDB
            '    Dim ThreadException As Exception = Nothing

            '    Dim Users = db.TAB.User.
            '    ToList()

            '    MyApp.WriteProcLog("BEGIN UPDATE QUERY USER ACCOUNT", AutoProcType.UPDATE_QUERY)


            '    For Each U In Users

            '        Dim Queries = U.Tab_Query.
            '            WhereOp("and", "or", "post_download_count", "=", -1, "last_Update", "<", Date.UtcNow.AddDays(-5)).
            '        ToList()

            '        'query non scaricate
            '        'query seguite ogni 1 giorni
            '        'query non seguite ogni 5 giorni
            '        U.Tab_Account.REL.Account.Auto_Follow_Query()

            '        If Queries.Count > 0 Then

            '            MyApp.WriteProcLog(SF("(tab)begin update query : {0}, number query: {1}", U.Name, Queries.Count), AutoProcType.UPDATE_QUERY)

            '            Dim Threads = New Utils.Threading.ThreadsManage(4)

            '            For Each q In Queries

            '                'scarico l'aggiorno l'eventuale riferimento geografico
            '                If q.Place_Id = 0 Then
            '                    Dim osm = New App.Network.OpenstreetMap
            '                    osm.DownloadPlace(q)
            '                End If


            '                Dim tw = New App.Network.Twitter
            '                ' passa il context corrente lo uso come ponte
            '                tw.HttpContextCurrent = HttpContext.Current

            '                Threads.Start(AddressOf tw.DownloadQueryPostsAsync, q.Id)

            '                If GetAsyncException("Exception_UpdateQuery") IsNot Nothing Then
            '                    Exit For
            '                End If

            '            Next

            '            'aspetta che finiscono tutti i thread
            '            Threads.WaitEnd()

            '            'se esiste una eccezione verifica se è perchè non ci sono + account per scaricare
            '            ThreadException = GetAsyncException("Exception_UpdateQuery")
            '            If ThreadException IsNot Nothing Then
            '                If ThreadException.GetType <> GetType(WebApi.Net.ExceptionTooManyRequestsAllAccount) Then
            '                    Throw ThreadException
            '                End If
            '            End If

            '            MyApp.WriteProcLog(SF("(tab)end update query: {0}", U.Name), AutoProcType.UPDATE_QUERY)

            '        End If

            '    Next

            '    MyApp.WriteProcLog("END UPDATE QUERY USER ACCOUNT", AutoProcType.UPDATE_QUERY)
            '    MyApp.WriteProcLog("----------------------------------------------------------", AutoProcType.UPDATE_QUERY)
            'End Sub

            Public Shared Sub QueryPosts()
                ' scarica i post delle query
                Dim db As mDB = mDB.GetDB
                Dim ThreadException As Exception = Nothing

                Dim Users = db.TAB.User.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE QUERY USER ACCOUNT", TaskType.UPDATE_QUERY)

                For Each U In Users

                    Dim QueryIds As New List(Of Integer)

                    'query non scaricate
                    QueryIds.AddRange(
                        U.View_Query.
                        Where("post_download_count", "=", -1).
                        SetSelect("query.id").
                    ToList(Of Integer)("id"))

                    'query in real-time
                    QueryIds.AddRange(
                        U.View_EnabledAccount.
                        REL.Account.Listen_Query.
                        REL.Listen_Query.Query.
                        Where("last_update", "<", Date.UtcNow.AddHours(-6)).
                        SetSelect("query_id").
                    ToList(Of Integer)("query_id"))

                    'query seguite dall'account dello user
                    QueryIds.AddRange(
                        U.View_EnabledAccount.
                        REL.Account.Auto_Follow_Query.
                        REL.Auto_Follow_Query.Query.
                        Where("last_update", "<", Date.UtcNow.AddHours(-6)).
                    ToList(Of Integer)("query_id"))

                    'compatti id
                    QueryIds = QueryIds.Distinct.ToList

                    If QueryIds.Count > 0 Then


                        MyApp.WriteProcLog(SF("(tab)begin update query : {0}, number query: {1}", U.ToString, QueryIds.Count), TaskType.UPDATE_QUERY)

                        QueryPostsUpdate(QueryIds, mDB.Query.UpdateModeType.NORMAL)

                        MyApp.WriteProcLog(SF("(tab)end update query: {0}", U.ToString), TaskType.UPDATE_QUERY)

                    End If

                Next

                MyApp.WriteProcLog("END UPDATE QUERY USER ACCOUNT", TaskType.UPDATE_QUERY)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_QUERY)
            End Sub

            Public Shared Sub QueryPostsUpdate(QueryIds As List(Of Integer), Mode As mDB.Query.UpdateModeType)
                Dim db As mDB = mDB.GetDB

                Dim Queries = db.TAB.Query.
                    Where("id", "IN", QueryIds).
                ToList()

                '--------------------------------------------------
                'TWITTER
                '--------------------------------------------------

                ' scarica i post delle query
                Dim ThreadException As Exception = Nothing
                Dim Threads = New Utils.Threading.ThreadsManage(2)


                For Each q In MyApp.NetFilter(Queries, MyApp.Network.NetTypeToAccTypes(WebApi.Type.TWITTER))

                    'scarico l'aggiorno l'eventuale riferimento geografico
                    If q.Place_Id = 0 Then
                        Dim osm = New MyApp.Network.OpenstreetMap
                        osm.DownloadPlace(q)
                    End If

                    Dim tw = New MyApp.Network.Twitter
                    ' passa il context corrente lo uso come ponte
                    tw.HttpContextCurrent = HttpContext.Current

                    Threads.Start(AddressOf tw.DownloadQueryPostsAsync, New With {.QueryID = q.Id, .Mode = Mode})

                    If GetAsyncException("Exception_UpdateQuery") IsNot Nothing Then
                        Exit For
                    End If

                Next

                'aspetta che finiscono tutti i thread
                Threads.WaitEnd()

                'se esiste una eccezione verifica se è perchè non ci sono + account per scaricare
                ThreadException = GetAsyncException("Exception_UpdateQuery")
                If ThreadException IsNot Nothing Then
                    If ThreadException.GetType <> GetType(WebApi.Net.ExceptionTooManyRequestsAllAccount) Then
                        Throw ThreadException
                    End If
                End If

                '--------------------------------------------------
                'FACEBOOK
                '--------------------------------------------------
                For Each q In MyApp.NetFilter(Queries, MyApp.Network.NetTypeToAccTypes(WebApi.Type.FACEBOOK))

                    'scarico l'aggiorno l'eventuale riferimento geografico
                    If q.Place_Id = 0 Then
                        Dim osm = New MyApp.Network.OpenstreetMap
                        osm.DownloadPlace(q)
                    End If


                    Dim fb = New MyApp.Network.Facebook

                    Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.SEARCH, Network.AccType.FACEBOOK_PAGE)
                    fb.oauth2 = UserAcc.getOauth2

                    fb.DownloadQueryPosts(q, mDB.Query.UpdateModeType.NORMAL)
                    Task.Elaborate.CreateIndexQueryPosts(q.Id)

                Next

                '--------------------------------------------------
                'GOOGLE+
                '--------------------------------------------------
                For Each q In MyApp.NetFilter(Queries, MyApp.Network.NetTypeToAccTypes(WebApi.Type.GOOGLE))

                    'scarico l'aggiorno l'eventuale riferimento geografico
                    If q.Place_Id = 0 Then
                        Dim osm = New MyApp.Network.OpenstreetMap
                        osm.DownloadPlace(q)
                    End If


                    Dim g = New MyApp.Network.Google

                    Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.SEARCH, Network.AccType.GOOGLE_PEOPLE)
                    g.oauth2 = UserAcc.getOauth2

                    g.DownloadQueryPosts(q, GloukDB.Query.UpdateModeType.NORMAL)

                    Task.Elaborate.CreateIndexQueryPosts(q.Id)

                Next



            End Sub
            'Public Shared Sub QueryPostsRealTime()
            '    ' scarica i post delle query
            '    Dim db As mDB = mDB.GetDB

            '    Dim QueryIds = db.TAB.Query.BY.Query.Real_Time(1).ToList(Of Integer)("id")


            '    If QueryIds.Count > 0 Then

            '        QueryPostsUpdate(QueryIds, mDB.Query.UpdateModeType.REALTIME)

            '    End If

            'End Sub

            'Public Shared Sub UserPlaceTwitter()
            '    Dim db As mDB = mDB.GetDB
            '    Dim tw = New App.Network.Twitter

            '    Dim Accounts =
            '        db.TAB.Account.
            '        REL.Account.User_Account.
            '    ToList()

            '    MyApp.WriteProcLog("BEGIN UPDATE PLACE USER ACCOUNT", AutoProcType.UPDATE_ACCOUNTS)

            '    For Each Acc In Accounts

            '        Dim Accs = db.TAB.Account.
            '            REL.Account.Account_Add_Info.
            '            REL.Account.Account_Link.
            '            BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
            '            Where("Place_Id", "=", 0).
            '        ToList()

            '        Dim UpdatePlace = True

            '        If Accs.Count > 0 Then
            '            MyApp.WriteProcLog(SF("(tab)begin update place: {0}, number users: {1}", Acc.Fullname, Accs.Count), AutoProcType.UPDATE_ACCOUNTS)

            '            Try

            '                For Each A In Accs

            '                    tw.DownloadPlace(A)

            '                Next

            '            Catch ex As WebApi.Net.ExceptionTooManyRequestsAllAccount

            '                MyApp.WriteProcLog(SF("(tab)(tab)error update share details : ExceptionTooManyRequestsAllAccount"), AutoProcType.UPDATE_ACCOUNTS)
            '                UpdatePlace = False

            '            End Try

            '            'aggiorna l'analisi place del followers
            '            App.Data.Elaborate.AnalysisFollowersPlace(Acc)

            '        End If

            '        If UpdatePlace Then

            '        End If
            '    Next

            '    MyApp.WriteProcLog("END UPDATE PLACE USER ACCOUNT", AutoProcType.UPDATE_ACCOUNTS)
            '    MyApp.WriteProcLog("----------------------------------------------------------", AutoProcType.UPDATE_ACCOUNTS)


            'End Sub
            Public Shared Sub AccountPlaces()
                Const MacAccountsUpdate = 1000
                Dim db As mDB = mDB.GetDB
                Dim osm = New MyApp.Network.OpenstreetMap

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE PLACE USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)

                For Each Acc In Accounts

                    Dim Accs = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        REL.Account.Account_Add_Info.
                        Where("Place_Id", "=", 0).
                        SetSelect("Account.*").
                        Limit(MacAccountsUpdate).
                    ToList(Of mDB.Account)()

                    Dim UpdatePlace = False

                    If Accs.Count > 0 Then
                        UpdatePlace = True
                        MyApp.WriteProcLog(SF("(tab)begin update place: {0}, number users: {1}", Acc.ToString, Accs.Count), TaskType.UPDATE_ACCOUNTS)

                        For Each A In Accs

                            Try

                                osm.DownloadPlace(A)

                            Catch ex As WebApi.Net.ExceptionAPI

                                MyApp.WriteProcLog(SF("(tab)(tab)error update share details : ExceptionAPI"), TaskType.UPDATE_ACCOUNTS)
                                UpdatePlace = False

                            End Try

                        Next

                    End If

                    If UpdatePlace Then

                    End If
                Next

                MyApp.WriteProcLog("END UPDATE PLACE USER ACCOUNT", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)


            End Sub

            Public Shared Sub FeedRss()
                Dim db As mDB = mDB.GetDB
                Dim tw = New MyApp.Network.FeedRss

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()


                MyApp.WriteProcLog("BEGIN UPDATE FEED RSS", TaskType.UPDATE_ACCOUNTS)

                For Each Acc In Accounts

                    Dim feed = Acc.Tab_Task_Send.
                        REL.Task_Send.FeedRss.
                        Where("task_send.expired_task", "=", False).
                        Where("task_send.enabled_task", "=", True).
                        Where("item_update", "<", Date.UtcNow.AddHours(-1)).
                        SetSelect("feedrss.*").
                    ToList(Of mDB.Feedrss)()

                    If feed.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update feedrss: {0}, number users: {1}", Acc.ToString, feed.Count), TaskType.UPDATE_ACCOUNTS)


                        For Each f In feed

                            tw.DownloadRss(f)

                        Next

                        MyApp.WriteProcLog(SF("(tab)end update account: {0}", Acc.Fullname), TaskType.UPDATE_ACCOUNTS)


                    End If


                Next



                MyApp.WriteProcLog("END UPDATE FEED RSS", TaskType.UPDATE_ACCOUNTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_ACCOUNTS)



            End Sub

            Private Shared Function GetAsyncException(ExName As String) As Exception
                Return DirectCast(HttpContext.Current.Items(ExName), Exception)
            End Function


        End Class

        Public Class Send

#Region "POST"


            Public Shared Function SendPost(CurrAccount As mDB.Account, post As mDB.Task_Post) As Object


                Dim res As Object = Nothing

                Dim net = MyApp.Network.AccTypeToNetType(CurrAccount.Network_Id)

                Select Case net
                    Case WebApi.Type.TWITTER

                        Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

                        res = tw.SendPost(CurrAccount, post)

                    Case WebApi.Type.BUFFER

                        Dim buf = New MyApp.Network.Buffer(CurrAccount.GetOauth2)

                        res = buf.SendPost(CurrAccount, post)
                        'Catch ex As WebApi.Net.ExceptionAPIResponse

                    Case Else

                        'Throw New WebApi.Net.ExceptionAPI

                End Select

                Return res

            End Function

            Public Shared Function RemovePost(CurrAccount As mDB.Account, PostCode As String, PosType As mDB.Task_Post.Type) As Object


                Dim res As Object = Nothing

                Dim net = MyApp.Network.AccTypeToNetType(CurrAccount.Network_Id)

                'IMPORTANTE se devo rimuove uno share devo prendere il codice del post creato dallo share 
                If PosType = GloukDB.Task_Post.Type.SHARE Then
                    Dim ShareDett = CurrAccount.GetShareDettFromPost(PostCode)
                    If ShareDett IsNot Nothing Then
                        PostCode = ShareDett.Post_Code
                    End If
                End If

                Select Case net
                    Case WebApi.Type.TWITTER

                        Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)
                        res = tw.RemovePost(CurrAccount, PostCode, PosType)

                    Case Else

                        'Throw New WebApi.Net.ExceptionAPI

                End Select

                Return res

            End Function


            Public Shared Sub AccountSchedulePosts()
                Dim db As mDB = mDB.GetDB
                'Dim tw = New MyApp.Network.Twitter

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()
                '                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).


                MyApp.WriteProcLog("BEGIN SEND POST", TaskType.SEND_POSTS)

                'cliclo dei account
                For Each Acc In Accounts

                    'task scaduti per ogni account
                    Dim Tasks = Acc.Tab_Task_Send.
                        Where("next_send_date", "<", Date.UtcNow, "next_send_date", ">", Date.UtcNow.AddMonths(-1)).
                        Where("enabled_task", "=", True).
                    ToList

                    If Tasks.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin send post : {0}, task scaduti: {1}", Acc.ToString, Tasks.Count), TaskType.SEND_POSTS)

                        'tw.oauth = Acc.getOauth

                        'cliclo task scaduti
                        For Each taskSend In Tasks

                            Dim EndSend = False

                            'ciclo della spedizione post
                            Do Until EndSend

                                'controllo del massimo di post giorno  spedibili, se 0 infiniti
                                If taskSend.CheckSendPostDayLimit Then
                                    EndSend = True
                                Else
                                    'post da spedire
                                    Dim post = taskSend.GetNextPost
                                    'verifica se ci sono post ancora da spedire
                                    If post IsNot Nothing Then

                                        Try

                                            'tw.SendPost(post.Post_Text, post.To_Account_Username, post.Private_Post)
                                            If taskSend.Debug_Task Then
                                                Dim u = Acc.Tab_User_Account.REL.User_Account.User.SetSelect("user.*").ToObj(Of mDB.User)()
                                                If u IsNot Nothing Then
                                                    MyApp.Email.Debug.Send(SF("(tab)(tab)send post : '{0}', to: {1}, type: {2}", post.Post_Text, post.To_Account_Username, post.Post_Type_Id), u.Email)
                                                End If
                                                'MyApp.SendDebugMail(SF("(tab)(tab)send post : '{0}', to: {1}, type: {2}", post.Post_Text, post.To_Account_Username, post.Post_Type_Id))
                                            Else
                                                MyApp.Task.Send.SendPost(Acc, post)
                                                'tw.SendPost(post)
                                            End If
                                            post.Last_Send_Result = "OK"

                                        Catch ex As WebApi.Net.ExceptionAPI

                                            'MyApp.WriteProcLog(SF("(tab)(tab)error send post: ExceptionServiceBase: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.SEND_POSTS)

                                            post.Last_Send_Result = SF("{0}, {1}", ex.ServiceError.Code, Mid(ex.ServiceError.Message, 1, 240))

                                        End Try

                                        post.Last_Send_Date = Date.UtcNow
                                        post.Send_Post = True 'db.ToBool(True)
                                        db.SubmitChanges()

                                        'IMPORTANTE prima di tutto incremento il contatore giornaliero
                                        If taskSend.Last_Send_Date.Date = Date.UtcNow.Date Then
                                            taskSend.Post_Send_Count += 1
                                        Else
                                            taskSend.Post_Send_Count = 1
                                        End If

                                        taskSend.Last_Send_Date = Date.UtcNow
                                        taskSend.Last_Send_Post = post.Post_Text
                                        taskSend.Last_Send_Result = post.Last_Send_Result

                                        'IMPOERTANTE finisco di spedire eventuali post in coda se è attivato un intervallo di tempo e se non sto facendo share di post
                                        If Not taskSend.Send_All_Post Then
                                            taskSend.SetNextSend()
                                            EndSend = True
                                        End If

                                    Else
                                        'verifico se devo ricomciare la spedizione
                                        If taskSend.Repeat_Send_Post Then
                                            'se devo ricominciare resetto tutto
                                            taskSend.ResetAllPosts()
                                        Else
                                            ' se non ho + post da inviare e non devo ripetere l'invio allora il task è concluso
                                            taskSend.Close()
                                            EndSend = True
                                        End If
                                    End If

                                    db.SubmitChanges()

                                End If


                            Loop
                        Next

                        MyApp.WriteProcLog(SF("(tab)end send post : {0}", Acc.Fullname), TaskType.SEND_POSTS)

                    End If

                Next

                MyApp.WriteProcLog("END SEND POST", TaskType.SEND_POSTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.SEND_POSTS)

            End Sub

            Public Shared Sub AccountPosts_old()
                Dim db As mDB = mDB.GetDB
                Dim tw = New MyApp.Network.Twitter

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN SEND POST", TaskType.SEND_POSTS)

                'cliclo dei account
                For Each Acc In Accounts

                    'task scaduti per ogni account
                    Dim Tasks = Acc.Tab_Task_Send.
                        Where("next_send_date", "<", Date.UtcNow, "next_send_date", ">", Date.UtcNow.AddMonths(-1)).
                        Where("enabled_task", "=", True).
                    ToList

                    If Tasks.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin send post : {0}, task scaduti: {1}", Acc.ToString, Tasks.Count), TaskType.SEND_POSTS)

                        tw.oauth = Acc.GetOauth

                        'cliclo task scaduti
                        For Each taskSend In Tasks

                            Dim EndSend = False

                            'ciclo della spedizione post
                            Do Until EndSend



                                'controllo del massimo di post giorno  spedibili, se 0 infiniti
                                If taskSend.CheckSendPostDayLimit Then
                                    EndSend = True
                                Else
                                    'post da spedire
                                    Dim post = taskSend.GetNextPost
                                    'verifica se ci sono post ancora da spedire
                                    If post IsNot Nothing Then

                                        Try

                                            'tw.SendPost(post.Post_Text, post.To_Account_Username, post.Private_Post)
                                            If taskSend.Debug_Task Then
                                                Dim u = Acc.Tab_User_Account.REL.User_Account.User.SetSelect("user.*").ToObj(Of mDB.User)()
                                                If u IsNot Nothing Then
                                                    MyApp.Email.Debug.Send(SF("(tab)(tab)send post : '{0}', to: {1}, type: {2}", post.Post_Text, post.To_Account_Username, post.Post_Type_Id), u.Email)
                                                End If
                                                'MyApp.SendDebugMail(SF("(tab)(tab)send post : '{0}', to: {1}, type: {2}", post.Post_Text, post.To_Account_Username, post.Post_Type_Id))
                                            Else
                                                tw.SendPost(Acc, post)
                                            End If
                                            post.Last_Send_Result = "OK"

                                        Catch ex As WebApi.Net.ExceptionAPI

                                            'MyApp.WriteProcLog(SF("(tab)(tab)error send post: ExceptionServiceBase: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.SEND_POSTS)

                                            post.Last_Send_Result = SF("{0}, {1}", ex.ServiceError.Code, Mid(ex.ServiceError.Message, 1, 240))

                                        End Try

                                        post.Last_Send_Date = Date.UtcNow
                                        post.Send_Post = True 'db.ToBool(True)
                                        db.SubmitChanges()

                                        'IMPORTANTE prima di tutto incremento il contatore giornaliero
                                        If taskSend.Last_Send_Date.Date = Date.UtcNow.Date Then
                                            taskSend.Post_Send_Count += 1
                                        Else
                                            taskSend.Post_Send_Count = 1
                                        End If

                                        taskSend.Last_Send_Date = Date.UtcNow
                                        taskSend.Last_Send_Post = post.Post_Text
                                        taskSend.Last_Send_Result = post.Last_Send_Result

                                        'IMPOERTANTE finisco di spedire eventuali post in coda se è attivato un intervallo di tempo e se non sto facendo share di post
                                        If Not taskSend.Send_All_Post Then
                                            taskSend.SetNextSend()
                                            EndSend = True
                                        End If

                                    Else
                                        'verifico se devo ricomciare la spedizione
                                        If taskSend.Repeat_Send_Post Then
                                            'se devo ricominciare resetto tutto
                                            taskSend.ResetAllPosts()
                                        Else
                                            ' se non ho + post da inviare e non devo ripetere l'invio allora il task è concluso
                                            taskSend.Close()
                                            EndSend = True
                                        End If
                                    End If

                                    db.SubmitChanges()

                                End If


                            Loop
                        Next

                        MyApp.WriteProcLog(SF("(tab)end send post : {0}", Acc.Fullname), TaskType.SEND_POSTS)

                    End If

                Next

                MyApp.WriteProcLog("END SEND POST", TaskType.SEND_POSTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.SEND_POSTS)

            End Sub



#End Region

            '#Region "SHARE POST"

            'Public Shared Sub UsersSharePost()

            'Dim db As mDB = mDB.GetDB
            'Dim tw = New App.Network.Twitter

            'Dim Accounts =
            '    db.TAB.Account.
            '    REL.Account.User_Account.
            'ToList()

            'MyApp.WriteProcLog("BEGIN SHARE POST", AutoProcType.SEND_POSTS)

            'For Each Acc In Accounts

            '    'Dim Accs = Acc.Tab_AccountLink(mDB.Account_Link.Type.TO_POST_SHARE)

            '    'trova tutti gli followers da agiornare i post
            '    Dim AccLinks =
            '        db.TAB.Account.
            '        REL.Account.Account_Update.
            '        REL.Account.Account_Link.
            '        BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.TO_POST_SHARE).
            '        Where("update_int <> post_update_count").
            '        Where("update_date", "<", Date.UtcNow.AddHours(-1)).
            '        SetSelect("account_link.*").
            '    ToList(Of mDB.Account_Link)()

            '    If AccLinks.Count > 0 Then

            '        MyApp.WriteProcLog(SF("(tab)begin share post : {0}, account number: {1}", Acc.Fullname, AccLinks.Count), AutoProcType.SEND_POSTS)

            '        tw.oauth = Acc.getOauth

            '        For Each al In AccLinks
            '            Dim LastPost = tw.SendShareAccountPost(al.Account_Link_Id, al.Update_Str)

            '            If LastPost IsNot Nothing Then
            '                al.Update_Date = Date.UtcNow
            '                al.Update_Str = LastPost.Post_Code
            '                al.Update_Int = db.TAB.Account_Update.GetByPK(al.Account_Link_Id).Post_Update_Count
            '                db.SubmitChanges()
            '            End If
            '        Next

            '    End If


            'Next

            'MyApp.WriteProcLog("END SHARE POST", AutoProcType.SEND_POSTS)
            'MyApp.WriteProcLog("----------------------------------------------------------", AutoProcType.SEND_POSTS)


            'End Sub

            '#End Region

#Region "AUTO FOLLOW"

            ' private

            'Public Shared Sub FollowUnfollowAccount()
            '    Dim FollowDayLimit = 50
            '    Dim UnFollowDayLimit = 150

            '    Dim db As mDB = mDB.GetDB
            '    Dim tw = New MyApp.Network.Twitter


            '    Dim Accounts = db.VIEW.Account_UserEnabled.
            '        BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
            '    ToList()

            '    MyApp.WriteProcLog("BEGIN FOLLOW/UNFOLLOW ACCOUNT", TaskType.AUTO_FOLLOW)

            '    For Each Acc In Accounts


            '        '-----------------------------------------------------------
            '        'aggiunge i follow
            '        Dim TotToFoll = Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.PENDING).SetSelect("count(*) as Tot").ToObj(Of Integer)()

            '        If TotToFoll > 0 Then
            '            FollowDayLimit = Acc.Account_Option.Follow_Day_Limit
            '            If FollowDayLimit = 0 Then
            '                FollowDayLimit = 50
            '            End If

            '            tw.oauth = Acc.GetOauth

            '            Dim TotFollLastDay = Acc.GetFriendCount(1) 'Acc.Tab_Auto_Follow_Account.Where("follow_date", ">", Date.UtcNow.AddDays(-1)).SetSelect("count(*) as Tot").ToObj(Of Integer)()
            '            Dim ToFollowers = FollowDayLimit - TotFollLastDay

            '            If ToFollowers <= 0 Then

            '                MyApp.WriteProcLog(SF("(tab)day follower limit : {0}, to follower: ({1}), last day: ({2})", Acc.ToString, TotToFoll, TotFollLastDay), TaskType.AUTO_FOLLOW)

            '            Else

            '                Dim FollAccAll = Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.PENDING).
            '                    OrderBy("update_status_date").
            '                ToList()

            '                Dim FillAccFoll = New mDB.Auto_Follow_Account.FillList
            '                FillAccFoll.InputList = FollAccAll
            '                FillAccFoll.Types.Add(mDB.Auto_Follow_Account.SourceType.QUERY, (ToFollowers * 0.5) + 1)
            '                FillAccFoll.Types.Add(mDB.Auto_Follow_Account.SourceType.PROFILE_FOLLOWER, (ToFollowers * 0.5) + 1)
            '                Dim FollAcc = FillAccFoll.FillList()

            '                'Exit Sub

            '                MyApp.WriteProcLog(SF("(tab)add follow : {0}, follow number: ({1}), last day: ({2})", Acc.ToString, FollAcc.Count, TotFollLastDay), TaskType.AUTO_FOLLOW)

            '                'prima di fare il follow controllo la relazione con questi account
            '                Dim Rel = tw.DownloadRelationships(FollAcc.Select(Function(o) o.Account_To_Foll_Code).ToList)

            '                Dim FollError = 0

            '                For Each fa In FollAcc
            '                    'verifico se già è seguito
            '                    If Rel.ContainsKey("following") AndAlso Rel("following").ContainsKey(fa.Account_To_Foll_Code) Then
            '                        'agg DB
            '                        fa.Update_Status_Date = Date.UtcNow
            '                        fa.Status_Id = mDB.Auto_Follow_Account.StatusType.ALREADY_FRIEND
            '                        MyApp.WriteProcLog(SF("(tab)(tab)already friend: '{0}'", fa.Account_To_Foll_Code), TaskType.AUTO_FOLLOW)
            '                    Else

            '                        'Else
            '                        Try
            '                            tw.FollowAccont(Acc, fa.Account_To_Foll_Code)

            '                            fa.Follow_Date = Date.UtcNow
            '                            fa.Update_Status_Date = Date.UtcNow
            '                            fa.Status_Id = mDB.Auto_Follow_Account.StatusType.FOLLOW
            '                            MyApp.WriteProcLog(SF("(tab)(tab)follow: '{0}', Source: [{1}-{2}]", fa.Account_To_Foll_Code, fa.Source_Type_Id, fa.Source_Id), TaskType.AUTO_FOLLOW)

            '                        Catch ex As WebApi.Net.ExceptionAPIResponse

            '                            If ex.ServiceError.Code = 161 Then
            '                                FollError += 1
            '                            Else
            '                                fa.Update_Status_Date = Date.UtcNow
            '                                fa.Status_Id = mDB.Auto_Follow_Account.StatusType.ERROR
            '                            End If
            '                            MyApp.WriteProcLog(SF("(tab)(tab)error: '{0}'", fa.Account_To_Foll_Code), TaskType.AUTO_FOLLOW)

            '                        End Try


            '                    End If

            '                    db.SubmitChanges()

            '                    If FollError >= 1 Then
            '                        MyApp.WriteProcLog(SF("(tab)(tab)error follower system limit"), TaskType.AUTO_FOLLOW)
            '                        Exit For
            '                    End If

            '                Next
            '            End If

            '        End If

            '        '-----------------------------------------------------------
            '        ' unfollow di chi non è diventato un follower

            '        Dim UnFollAcc = Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.FOLLOW).
            '            Where("follow_date", "<", Date.UtcNow.AddDays(-6)).
            '        ToList()

            '        If UnFollAcc.Count > 0 Then

            '            UnFollowDayLimit = Acc.Account_Option.Unfollow_Day_Limit
            '            If UnFollowDayLimit = 0 Then
            '                UnFollowDayLimit = 150
            '            End If

            '            tw.oauth = Acc.GetOauth

            '            Dim TotUnFollLastDay = Acc.GetUnfollowCount(1)  'Acc.Tab_Auto_Follow_Account.Where("unfollow_date", ">", Date.UtcNow.AddDays(-1)).SetSelect("count(*) as Tot").ToObj(Of Integer)()

            '            If TotUnFollLastDay >= UnFollowDayLimit Then

            '                MyApp.WriteProcLog(SF("(tab)day unfollower limit: {0}, follow number: ({1}), last day: ({2})", Acc.ToString, UnFollAcc.Count, TotUnFollLastDay), TaskType.AUTO_FOLLOW)

            '            Else

            '                MyApp.WriteProcLog(SF("(tab)remove follow: {0}, unfollow number: ({1}), last day: ({2})", Acc.ToString, UnFollAcc.Count, TotUnFollLastDay), TaskType.AUTO_FOLLOW)

            '                For Each fa In UnFollAcc

            '                    If TotUnFollLastDay >= UnFollowDayLimit Then
            '                        MyApp.WriteProcLog(SF("(tab)(tab)error unfoll day limit: '{0}'", fa.Account_To_Foll_Code), TaskType.AUTO_FOLLOW)
            '                        'ATTENZIONE se supero la soglia esco dal ciclo
            '                        Exit For
            '                    Else

            '                        Try

            '                            Dim AccCode = tw.UnFollowAccont(Acc, fa.Account_To_Foll_Code)
            '                            TotUnFollLastDay += 1

            '                            fa.Status_Id = mDB.Auto_Follow_Account.StatusType.UNFOLLOW
            '                            MyApp.WriteProcLog(SF("(tab)(tab)unfollow: '{0}'", fa.Account_To_Foll_Code), TaskType.AUTO_FOLLOW)

            '                        Catch ex As Exception

            '                            fa.Status_Id = mDB.Auto_Follow_Account.StatusType.ERROR
            '                            MyApp.WriteProcLog(SF("(tab)(tab)unknow: '{0}'", fa.Account_To_Foll_Code), TaskType.AUTO_FOLLOW)

            '                        End Try

            '                        fa.Unfollow_Date = Date.UtcNow
            '                        fa.Update_Status_Date = Date.UtcNow
            '                        db.SubmitChanges()

            '                    End If

            '                Next

            '            End If

            '        End If


            '    Next

            '    MyApp.WriteProcLog("END FOLLOW/UNFOLLOW ACCOUNT", TaskType.AUTO_FOLLOW)
            '    MyApp.WriteProcLog("----------------------------------------------------------", TaskType.AUTO_FOLLOW)


            'End Sub


#End Region

#Region "FAVORITE"

            Public Shared Function AddFavotirePost(CurrAccount As mDB.Account, postCode As String) As mDB.Favorite_Post


                Dim res As mDB.Favorite_Post = Nothing

                Dim net = MyApp.Network.AccTypeToNetType(CurrAccount.Network_Id)

                Select Case net
                    Case WebApi.Type.TWITTER

                        Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

                        res = tw.AddFavoritePost(CurrAccount, postCode)


                    Case Else

                        'Throw New WebApi.Net.ExceptionAPI

                End Select

                Return res

            End Function
            Public Shared Function RemoveFavotirePost(CurrAccount As mDB.Account, postCode As String) As mDB.Favorite_Post


                Dim res As mDB.Favorite_Post = Nothing

                Dim net = MyApp.Network.AccTypeToNetType(CurrAccount.Network_Id)

                Select Case net
                    Case WebApi.Type.TWITTER

                        Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

                        tw.RemoveFavoritePost(CurrAccount, postCode)


                    Case Else

                        'Throw New WebApi.Net.ExceptionAPI

                End Select

                Return res

            End Function

#End Region


#Region "EMAIL"

            Public Shared Sub SendSystemEmail()
                Dim db As mDB = mDB.GetDB
                'Dim tw = New MyApp.Network.Twitter

                Dim EmailToSend = db.TAB.Send_Mail.BY.Send_Mail.Mail_Send(False).ToList

                MyApp.WriteProcLog("BEGIN SEND EMAIL", TaskType.SEND_POSTS)

                For Each SendMail In EmailToSend

                    MyApp.WriteProcLog(SF("(tab)send mail: {0}, data: {1}", SendMail.Mail_Type.ToString, SendMail.Data_Json), TaskType.SEND_POSTS)
                    SendMail.SendMail()

                Next

                MyApp.WriteProcLog("END SEND EMAIL", TaskType.SEND_POSTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.SEND_POSTS)


            End Sub

#End Region



        End Class

        Public Class Elaborate

#Region "TRENDS"

            Public Shared Sub CreateTrend(Excecute As Boolean)
                Dim db As mDB = mDB.GetDB


                'Dim Yesterday = Today.AddDays(-1)
                'Dim Trend As mDB.Trend


                MyApp.WriteProcLog("BEGIN TREND USER ACCOUNT", TaskType.ELABORATE_DATA)

                'trova tutti gli account da agiornare i post
                Dim Accs = db.VIEW.Account_UserEnabled.
                    REL.Account.Account_Update.
                ToList()


                For Each Acc In Accs

                    Dim Today = Date.UtcNow.Date

                    MyApp.WriteProcLog(SF("(tab)begin trend user account: {0}", Acc.ToString), TaskType.ELABORATE_DATA)

                    'da verificare la data di agg del profilo
                    If Acc.Account_Add_Info.Profile_Update > Today Then

                        '----------------------------------------------------
                        'post fatti
                        '----------------------------------------------------
                        If Acc.AddTrend(mDB._Trend.Type.POST_ABS, Today, Acc.Account_Add_Info.Post_Count) Then
                            MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.POST_ABS.ToString, Today), TaskType.ELABORATE_DATA)
                        End If

                        '----------------------------------------------------
                        'followers        
                        '----------------------------------------------------
                        If Acc.AddTrend(mDB._Trend.Type.FOLLOWER_ABS, Today, Acc.Account_Add_Info.Follower_Count) Then
                            MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.FOLLOWER_ABS.ToString, Today), TaskType.ELABORATE_DATA)
                        End If

                        '----------------------------------------------------
                        'auto follow query
                        '----------------------------------------------------
                        Dim EndTrend = False
                        Dim CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendAutoFollowAccountQuery(CurrDateTrend, Acc)
                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                            'server per forzare sempre almeno 10 giorni indietro
                            If CurrDateTrend.AddDays(10) > Today And Excecute Then
                                EndTrend = False
                            End If

                        Loop Until EndTrend

                        '----------------------------------------------------
                        'status                        
                        '----------------------------------------------------
                        If Acc.AddTrend(
                            mDB._Trend.Type.STATUS_FAKE, Today,
                            Acc.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.STATUS, mDB.Account.StatusType.FAKE)
                        ) Then
                            'MyApp.WriteProcLog(SF("(tab)(tab)add trend user account: STATUS"), AutoProcType.ELABORATE_DATA)
                            MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", "STATUS", Today), TaskType.ELABORATE_DATA)

                        End If

                        Acc.AddTrend(
                            mDB._Trend.Type.STATUS_INACTIVE, Today,
                            Acc.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.STATUS, mDB.Account.StatusType.INACTIVE))

                        Acc.AddTrend(
                            mDB._Trend.Type.STATUS_LOW_ACTIVITY, Today,
                            Acc.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.STATUS, mDB.Account.StatusType.LOW_ACTIVITY))

                        Acc.AddTrend(
                            mDB._Trend.Type.STATUS_MEDIUM_ACTIVITY, Today,
                            Acc.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.STATUS, mDB.Account.StatusType.MEDIUM_ACTIVITY))

                        Acc.AddTrend(
                            mDB._Trend.Type.STATUS_HIGHT_ACTIVITY, Today,
                            Acc.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.STATUS, mDB.Account.StatusType.HIGHT_ACTIVITY))

                    End If


                    '----------------------------------------------------
                    'foll e unfollw per giorno
                    '----------------------------------------------------
                    If Acc.Account_Update.Follower_Update > Today Then

                        Dim EndTrend = False
                        Dim CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendFollUnfollDay(CurrDateTrend, Acc)
                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend

                    End If

                    '----------------------------------------------------
                    'post per giorno
                    '----------------------------------------------------
                    If Acc.Account_Add_Info.Post_Update > Today Then


                        Dim EndTrend = False
                        Dim CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendPostDay(CurrDateTrend, Acc)
                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend
                    End If

                    '----------------------------------------------------
                    'message
                    '----------------------------------------------------
                    If Acc.Account_Update.Message_Post_Update > Today Then

                        Dim EndTrend = False
                        Dim CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendMessageDay(CurrDateTrend, Acc)
                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend


                        '**** add trend soli reply
                        EndTrend = False
                        CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendReplyDay(CurrDateTrend, Acc)
                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend


                    End If

                    '----------------------------------------------------
                    'share
                    '----------------------------------------------------
                    If Acc.Account_Update.Share_Det_Update > Today Then

                        Dim EndTrend = False
                        Dim CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendShareDay(CurrDateTrend, Acc)
                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend

                    End If

                    ' IMPORTANTE vengono ceate solo dopo sono stati aggiornati i post share, message, e gli account collegati
                    'If Acc.Account_Update.Share_Det_Update > Today And
                    'Acc.Account_Update.Message_Post_Update > Today And
                    'Acc.Account_Add_Info.Post_Update > Today And
                    'Acc.Account_Update.Share_Det_Update < Acc.Account_Update.Profile_Related_Update And
                    'Acc.Account_Update.Message_Post_Update < Acc.Account_Update.Profile_Related_Update Then
                    If Acc.Account_Update.Profile_Related_Update > Today Then
                        '----------------------------------------------------
                        'engagement
                        '----------------------------------------------------
                        Dim EndTrend = False
                        Dim CurrDateTrend = Today.AddDays(-1)
                        Dim AddOneTrend = False

                        Do
                            EndTrend = Not AddTrendEngagementDay(CurrDateTrend, Acc)
                            If Not EndTrend Then
                                AddOneTrend = True
                            End If

                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend

                        '----------------------------------------------------
                        'impression
                        '----------------------------------------------------
                        EndTrend = False
                        CurrDateTrend = Today.AddDays(-1)

                        Do
                            EndTrend = Not AddTrendImpressionDay(CurrDateTrend, Acc)
                            If Not EndTrend Then
                                AddOneTrend = True
                            End If

                            CurrDateTrend = CurrDateTrend.AddDays(-1)
                            If CurrDateTrend.AddDays(90) < Today Then
                                EndTrend = True
                            End If
                        Loop Until EndTrend


                        'add email
                        If AddOneTrend Then
                            MyApp.Email.System.Queued(Email.System.Type.ACCOUNT_ADD_TREND, False, New With {.account_id = Acc.Id})
                        End If

                    End If

                Next

                MyApp.WriteProcLog("END TREND USER ACCOUNT", TaskType.ELABORATE_DATA)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)


            End Sub




            Private Shared Function AddTrendFollUnfollDay(d As Date, acc As mDB.Account) As Boolean


                Dim AddTrend = acc.AddTrend(mDB._Trend.Type.FOLLOWER_REL, d,
                    acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER, d, d.AddDays(1)).SetSelect("count(*)")
                )

                acc.AddTrend(mDB._Trend.Type.UNFOLLOWER_REL, d,
                    acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER_OLD, d, d.AddDays(1)).SetSelect("count(*)")
                )

                If AddTrend Then
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.FOLLOWER_REL.ToString, d), TaskType.ELABORATE_DATA)

                End If

                Return AddTrend



            End Function

            Private Shared Function AddTrendPostDay(d As Date, acc As mDB.Account) As Boolean

                Dim AddTrend = acc.AddTrend(mDB._Trend.Type.POST_REL, d,
                    acc._Tab_Account_Post.
                    Where("pubb_date", ">=", d).
                    Where("pubb_date", "<", d.AddDays(1)).
                    SetSelect("count(*)")
                )

                If AddTrend Then

                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.POST_REL.ToString, d), TaskType.ELABORATE_DATA)

                End If

                Return AddTrend

            End Function

            Private Shared Function AddTrendMessageDay(d As Date, acc As mDB.Account) As Boolean

                Dim AddTrend = acc.AddTrend(
                    mDB._Trend.Type.MESSAGE_REL, d,
                    acc.Tab_Message_Post.
                    Where("pubb_date", ">=", d).
                    Where("pubb_date", "<", d.AddDays(1)).
                    SetSelect("count(*)")
                )

                If AddTrend Then
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.MESSAGE_REL.ToString, d), TaskType.ELABORATE_DATA)
                End If

                Return AddTrend

                'Dim db As mDB = mDB.GetDB

                'Dim Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.MESSAGE_REL, d).ToObj

                'If Trend Is Nothing Then

                '    Dim TotMess = acc.Tab_Message_Post.
                '        Where("pubb_date", ">=", d).
                '        Where("pubb_date", "<", d.AddDays(1)).
                '        SetSelect("count(*)").
                '    ToObj(Of Integer)()

                '    Trend = New mDB.Trend With {
                '        .Account_Id = acc.Id,
                '        .Trend_Type_Id = mDB.Trend.Type.MESSAGE_REL,
                '        .Trend_Date = d,
                '        .Value = TotMess
                '    }
                '    db.TAB.Trend.InsertOnSubmit(Trend)
                '    MyApp.WriteProcLog(SF("(tab)(tab)add trend message user account:{0}, {1}", mDB.Trend.Type.MESSAGE_REL.ToString, d), AutoProcType.ELABORATE_DATA)

                '    db.SubmitChanges()

                '    Return True
                'Else
                '    Return False
                'End If


            End Function
            Private Shared Function AddTrendReplyDay(d As Date, acc As mDB.Account) As Boolean

                Dim AddTrend = acc.AddTrend(
                    mDB._Trend.Type.REPLY_REL, d,
                    acc.Tab_Message_Post.
                    Join("message_post", "post_code", "message_post.reply_to_post_code", "reply", "").
                    Where("message_post.pubb_date", ">=", d).
                    Where("message_post.pubb_date", "<", d.AddDays(1)).
                    Where("reply.account_id", "=", acc.Id).
                    SetSelect("count(*)")
                )

                If AddTrend Then
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.REPLY_REL.ToString, d), TaskType.ELABORATE_DATA)
                End If

                Return AddTrend

                'Dim db As mDB = mDB.GetDB

                'Dim Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.MESSAGE_REL, d).ToObj

                'If Trend Is Nothing Then

                '    Dim TotMess = acc.Tab_Message_Post.
                '        Where("pubb_date", ">=", d).
                '        Where("pubb_date", "<", d.AddDays(1)).
                '        SetSelect("count(*)").
                '    ToObj(Of Integer)()

                '    Trend = New mDB.Trend With {
                '        .Account_Id = acc.Id,
                '        .Trend_Type_Id = mDB.Trend.Type.MESSAGE_REL,
                '        .Trend_Date = d,
                '        .Value = TotMess
                '    }
                '    db.TAB.Trend.InsertOnSubmit(Trend)
                '    MyApp.WriteProcLog(SF("(tab)(tab)add trend message user account:{0}, {1}", mDB.Trend.Type.MESSAGE_REL.ToString, d), AutoProcType.ELABORATE_DATA)

                '    db.SubmitChanges()

                '    Return True
                'Else
                '    Return False
                'End If


            End Function
            'Private Shared Function AddTrendAutoFollowAccountQuery(d As Date, acc As mDB.Account) As Boolean
            '    Dim db As mDB = mDB.GetDB
            '    Dim AddTrend = False

            '    Dim Trend As mDB.Trend

            '    '-------------------------------------------------

            '    Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.AUTO_FOLLOW_ACCOUNT, d).ToObj

            '    Dim q = acc.Tab_Auto_Follow_Account.
            '        Where("follow_date", ">=", d).
            '        Where("follow_date", "<", d.AddDays(1)).
            '        SetSelect("count(*)")

            '    If Trend Is Nothing Then
            '        Trend = New mDB.Trend With {
            '            .Account_Id = acc.Id,
            '            .Trend_Type_Id = mDB.Trend.Type.AUTO_FOLLOW_ACCOUNT,
            '            .Trend_Date = d
            '        }
            '        db.TAB.Trend.InsertOnSubmit(Trend)

            '        AddTrend = True
            '    End If

            '    Trend.Value = q.Clone.ToObj(Of Integer)()

            '    db.SubmitChanges()

            '    '-------------------------------------------------

            '    Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.AUTO_FOLLOW_BECOME_FOLLOWER, d).ToObj

            '    If Trend Is Nothing Then
            '        Trend = New mDB.Trend With {
            '            .Account_Id = acc.Id,
            '            .Trend_Type_Id = mDB.Trend.Type.AUTO_FOLLOW_BECOME_FOLLOWER,
            '            .Trend_Date = d
            '        }
            '        db.TAB.Trend.InsertOnSubmit(Trend)

            '    End If

            '    Trend.Value = q.Clone.Where("status_id", "=", mDB.Auto_Follow_Account.StatusType.BECOME_FOLLOWER).ToObj(Of Integer)()

            '    db.SubmitChanges()

            '    '-------------------------------------------------


            '    Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.AUTO_FOLLOW_NOT_FOLLOWER, d).ToObj

            '    If Trend Is Nothing Then
            '        Trend = New mDB.Trend With {
            '            .Account_Id = acc.Id,
            '            .Trend_Type_Id = mDB.Trend.Type.AUTO_FOLLOW_NOT_FOLLOWER,
            '            .Trend_Date = d
            '        }
            '        db.TAB.Trend.InsertOnSubmit(Trend)

            '    End If

            '    Trend.Value = q.Clone.Where("status_id", "=", mDB.Auto_Follow_Account.StatusType.UNFOLLOW).ToObj(Of Integer)()

            '    db.SubmitChanges()

            '    '-------------------------------------------------

            '    MyApp.WriteProcLog(SF("(tab)(tab)add trend follow/unfollow user account:{0}, {1}", mDB.Trend.Type.SHARE_REL.ToString, d), AutoProcType.ELABORATE_DATA)

            '    Return AddTrend

            'End Function

            Private Shared Function AddTrendAutoFollowAccountQuery(d As Date, acc As mDB.Account) As Boolean


                '-------------------------------------------------

                Dim q = acc.Tab_Auto_Follow_Account.
                    Where("follow_date", ">=", d).
                    Where("follow_date", "<", d.AddDays(1)).
                    SetSelect("count(*)")

                '-------------------------------------------------

                Dim AddTrend = acc.AddTrend(
                    mDB._Trend.Type.AUTO_FOLLOW_ACCOUNT, d, q.Clone, True
                )

                '-------------------------------------------------

                acc.AddTrend(
                    mDB._Trend.Type.AUTO_FOLLOW_BECOME_FOLLOWER, d,
                    q.Clone.Where("status_id", "=", mDB.Auto_Follow_Account.StatusType.BECOME_FOLLOWER), True
                )

                '-------------------------------------------------

                acc.AddTrend(
                   mDB._Trend.Type.AUTO_FOLLOW_NOT_FOLLOWER, d,
                   q.Clone.Where("status_id", "=", mDB.Auto_Follow_Account.StatusType.UNFOLLOW), True
                )


                '-------------------------------------------------
                If AddTrend Then
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", "AUTO_FOLLOW".ToString, d), TaskType.ELABORATE_DATA)
                End If

                Return AddTrend

            End Function

            Private Shared Function AddTrendShareDay(d As Date, acc As mDB.Account) As Boolean
                Dim db As mDB = mDB.GetDB

                Dim AddTrend = acc.AddTrend(
                    mDB._Trend.Type.SHARE_REL, d,
                    db.TAB.Share_Post.
                    REL.Share_Post.Share_Detail.
                    BY.Share_Post.Account_Id(acc.Id).
                    Where("share_detail.pubb_date", ">=", d).
                    Where("share_detail.pubb_date", "<", d.AddDays(1)).
                    SetSelect("count(*)")
                )

                If AddTrend Then
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.SHARE_REL.ToString, d), TaskType.ELABORATE_DATA)
                End If

                Return AddTrend


            End Function
            Private Shared Function AddTrendEngagementDay(d As Date, acc As mDB.Account) As Boolean
                Dim db As mDB = mDB.GetDB

                'Dim Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.ENGAGEMENT_REL, d).ToObj
                Dim Trend = acc._Tab_Trend(mDB._Trend.Type.ENGAGEMENT_REL, d).ToObj '   db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.ENGAGEMENT_REL, d).ToObj

                If Trend Is Nothing Then
                    'retweet
                    Dim DTTotMess = db.TAB.Account.
                        REL.Account.Account_Add_Info.
                        REL.Account.Share_Detail.
                        REL.Share_Detail.Share_Post.
                        BY.Share_Post.Account_Id(acc.Id).
                        Where("share_detail.pubb_date", ">=", d).
                        Where("share_detail.pubb_date", "<", d.AddDays(1)).
                        SetSelect("sum(follower_count)").
                    ToDataTable

                    Dim TotMess = 0

                    If DTTotMess.Rows(0)(0) IsNot DBNull.Value Then
                        TotMess = Utils.Conv.ToInt(DTTotMess.Rows(0)(0))
                    End If

                    'aggiunto di dati dei messaggi che in realtà sono dei share
                    DTTotMess = db.TAB.Account.
                        REL.Account.Account_Add_Info.
                        REL.Account.Message_Post.
                        BY.Message_Post.To_Account_Id(acc.Id).
                        Where("is_share", "=", True).
                        Where("pubb_date", ">=", d).
                        Where("pubb_date", "<", d.AddDays(1)).
                        SetSelect("sum(follower_count)").
                    ToDataTable()

                    If DTTotMess.Rows(0)(0) IsNot DBNull.Value Then
                        TotMess += Utils.Conv.ToInt(DTTotMess.Rows(0)(0))
                    End If

                    Trend = New mDB._Trend With {
                        .Account_Id = acc.Id,
                        .Trend_Type_Id = mDB._Trend.Type.ENGAGEMENT_REL,
                        .Trend_Date = d,
                        .Value = TotMess
                    }
                    'db.TAB._Trend.InsertOnSubmit(Trend)
                    db.InsertOnSubmit(acc.ArchiveTrend.Table_Name, Trend)
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.ENGAGEMENT_REL.ToString, d), TaskType.ELABORATE_DATA)

                    db.SubmitChanges()

                    Return True
                Else
                    Return False
                End If


            End Function
            Private Shared Function AddTrendImpressionDay(d As Date, acc As mDB.Account) As Boolean
                Dim db As mDB = mDB.GetDB

                'Dim Trend = db.TAB.Trend.BY.Trend.Account_Id(acc.Id, mDB.Trend.Type.IMPRESSION_REL, d).ToObj
                Dim Trend = acc._Tab_Trend(mDB._Trend.Type.IMPRESSION_REL, d).ToObj

                If Trend Is Nothing Then
                    'retweet
                    Dim DTTotMess = db.TAB.Account.
                        REL.Account.Account_Add_Info.
                        REL.Account.Share_Detail.
                        REL.Share_Detail.Share_Post.
                        BY.Share_Post.Account_Id(acc.Id).
                        Where("share_detail.pubb_date", ">=", d).
                        Where("share_detail.pubb_date", "<", d.AddDays(1)).
                        SetSelect("sum(follower_count)").
                    ToDataTable

                    Dim TotMess = 0

                    If DTTotMess.Rows(0)(0) IsNot DBNull.Value Then
                        TotMess = Utils.Conv.ToInt(DTTotMess.Rows(0)(0))
                    End If

                    'aggiunto di dati dei messaggi
                    DTTotMess = db.TAB.Account.
                        REL.Account.Account_Add_Info.
                        REL.Account.Message_Post.
                        BY.Message_Post.To_Account_Id(acc.Id).
                        Where("pubb_date", ">=", d).
                        Where("pubb_date", "<", d.AddDays(1)).
                        SetSelect("sum(follower_count)").
                    ToDataTable()

                    If DTTotMess.Rows(0)(0) IsNot DBNull.Value Then
                        TotMess += Utils.Conv.ToInt(DTTotMess.Rows(0)(0))
                    End If

                    'aggiunto di dati dei miei post moltiplicato per i miei follower
                    Dim FollTrend = acc._Tab_Trend(mDB._Trend.Type.FOLLOWER_ABS).
                        Where("trend_date", ">=", d).
                        OrderBy("trend_date").
                        Limit(1).
                    ToObj()


                    'Dim FollTrend = db.TAB.Trend.
                    '    BY.Trend.Account_Id(acc.Id, mDB._Trend.Type.FOLLOWER_ABS).
                    '    Where("trend_date", ">=", d).
                    '    OrderBy("trend_date").
                    '    Limit(1).
                    'ToObj

                    Dim FollCount = acc.Account_Add_Info.Follower_Count
                    If FollTrend IsNot Nothing Then
                        FollCount = FollTrend.Value
                    End If

                    Dim PostCount = acc._Tab_Account_Post.
                        Where("pubb_date", ">=", d).
                        Where("pubb_date", "<", d.AddDays(1)).
                        SetSelect("Count(*)").
                    ToObj(Of Integer)()

                    TotMess += FollCount * PostCount

                    Trend = New mDB._Trend With {
                        .Account_Id = acc.Id,
                        .Trend_Type_Id = mDB._Trend.Type.IMPRESSION_REL,
                        .Trend_Date = d,
                        .Value = TotMess
                    }
                    db.InsertOnSubmit(acc.ArchiveTrend.Table_Name, Trend)
                    MyApp.WriteProcLog(SF("(tab)(tab)add trend: '{0}', #{1}#", mDB._Trend.Type.IMPRESSION_REL.ToString, d), TaskType.ELABORATE_DATA)

                    db.SubmitChanges()

                    Return True
                Else
                    Return False
                End If


            End Function

#End Region

#Region "FOLLOWR ANALISYS"

            Public Shared Sub AnalysisFollowers(Excecute As Boolean)
                Dim db As mDB = mDB.GetDB

                If Excecute Then

                    Dim Accounts = db.VIEW.Account_UserEnabled.
                        REL.Account.Account_Update.
                        Where("Analysis_Follower_Update", "<", Date.UtcNow.AddDays(-1)).
                    ToList()

                    MyApp.WriteProcLog("BEGIN UPDATE ANALYSIS FOLLOWERS", TaskType.ELABORATE_DATA)

                    For Each Acc In Accounts

                        MyApp.WriteProcLog(SF("(tab)update follower analisys: {0}", Acc.ToString), TaskType.ELABORATE_DATA)

                        AnalysisFollowersLanguage(Acc)
                        AnalysisFollowersGender(Acc)
                        AnalysisFollowersBusiness(Acc)
                        AnalysisFollowersPlace(Acc)
                        AnalysisFollowersStatus(Acc)
                        AnalysisFollowersFollowersCount(Acc)

                        Acc.Account_Update.Analysis_Follower_Update = Date.UtcNow.Date
                        db.SubmitChanges()

                    Next

                    MyApp.WriteProcLog("END UPDATE ANALYSIS FOLLOWERS", TaskType.ELABORATE_DATA)
                    MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)

                End If


            End Sub

            Private Shared Sub AnalysisFollowersFollowersCount(Acc As mDB.Account)
                Dim db As mDB = mDB.GetDB

                Dim classcount As Integer() = {0, 25, 250, 1000, 5000, 10000, 99999999}

                MyApp.WriteProcLog(SF("(tab)(tab)update count class follower analisys"), TaskType.ELABORATE_DATA)

                Dim q = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info.
                    SetSelect("count(*)")

                For ct = 1 To classcount.Length - 1
                    q.Select(SF("sum(if(follower_count >= {0} and follower_count < {1},1,0)) as class_{2}", classcount(ct - 1), classcount(ct), ct))
                Next

                Dim dt = q.ToDataTable

                For ct = 1 To classcount.Length - 1
                    Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.FOLLOWERS_COUNT, ct, Utils.Conv.ToInt(dt.Rows(0)(SF("class_{0}", ct))))
                Next

            End Sub


#Region "GENDER"

            Public Shared Sub SetGenderAccounts()
                Const MaxAccountUpdate = 5000
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE GENDER", TaskType.ELABORATE_DATA)
                Dim Gender = db.TAB.Gender_Name.NotifyChanged(False).ToList
                Dim Language = db.TAB.Language.ToDictionary(Of String)("lang_code")

                For Each Acc In Accounts


                    Dim Accs = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        REL.Account.Account_Add_Info.
                        Where("gender_type_id", "=", mDB.Gender_Name.Type.NOT_ASSIGNED).
                        Limit(MaxAccountUpdate).
                    ToList(Of mDB.Account)()

                    If Accs.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update gender: {0}, number users: ({1})", Acc.ToString, Accs.Count), TaskType.ELABORATE_DATA)

                        'Dim ctacc = 0
                        'Dim g As mDB.Gender_Name.Type
                        For Each A In Accs

                            Dim g = mDB.Gender_Name.Type.UNKNOW
                            'Dim Lang = ""

                            Dim AccLang = "****"
                            If Language.ContainsKey(A.Account_Add_Info.Lang) Then
                                AccLang = Language(A.Account_Add_Info.Lang).Language_En
                            End If

                            For Each gen In Gender

                                'If (" " & MyApp.RemoveDiacritics(A.Fullname) & " ").IndexOf(" " & MyApp.RemoveDiacritics(gen.Name) & " ", StringComparison.CurrentCultureIgnoreCase) <> -1 Then

                                '    g = gen.Gender_Type_Id1

                                '    Select Case g
                                '        Case mDB.Gender_Name.Type.UNKNOW
                                '            g = gen.Gender_Type_Id2
                                '        Case mDB.Gender_Name.Type.UNISEX
                                '            If gen.Gender_Type_Id2 = mDB.Gender_Name.Type.MALE Or gen.Gender_Type_Id2 = mDB.Gender_Name.Type.FEMALE Then
                                '                g = gen.Gender_Type_Id2
                                '            End If

                                '    End Select

                                '    'esce solo se trova maschio o femmina se unisex continua
                                '    If g = mDB.Gender_Name.Type.FEMALE Or g = mDB.Gender_Name.Type.MALE Then
                                '        Exit For
                                '    End If
                                'End If

                                If (" " & MyApp.RemoveDiacritics(A.Fullname) & " ").IndexOf(" " & MyApp.RemoveDiacritics(gen.Name) & " ", StringComparison.CurrentCultureIgnoreCase) <> -1 Then

                                    Dim lang = ""
                                    If gen.Lang.IndexOf(AccLang, StringComparison.CurrentCultureIgnoreCase) <> -1 Then
                                        lang = AccLang
                                    End If

                                    If g <> GloukDB.Gender_Name.Type.FEMALE And g <> GloukDB.Gender_Name.Type.MALE Then
                                        g = gen.Gender_Type_Id
                                    End If

                                    If (lang <> "") Then
                                        g = gen.Gender_Type_Id
                                        Exit For
                                    End If


                                End If

                            Next

                            A.Account_Add_Info.Gender_Type_Id = g
                            db.SubmitChanges()

                            MyApp.WriteProcLog(SF("(tab)(tab)update gender: {0}, gender: '{1}'", A.ToString, g.ToString), TaskType.ELABORATE_DATA)


                        Next

                        'MyApp.WriteProcLog(SF("(tab)end update gender"), AutoProcType.ELABORATE_DATA)

                        'aggiorna l'analisi
                        'AnalysisFollowersGender(Acc)

                    End If

                Next

                MyApp.WriteProcLog("END UPDATE GENDER", TaskType.ELABORATE_DATA)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)



            End Sub
            Private Shared Sub AnalysisFollowersGender(Acc As mDB.Account)
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog(SF("(tab)(tab)update gender follower analisys"), TaskType.ELABORATE_DATA)

                Dim dt = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info.
                    GroupBy("gender_type_id").
                    SetSelect("gender_type_id", "count(gender_type_id) as Total").
                ToDataTable

                For Each dr In dt.Rows
                    Dim t As mDB.Gender_Name.Type = dr("gender_type_id")
                    Select Case t
                        Case mDB.Gender_Name.Type.MALE, mDB.Gender_Name.Type.FEMALE
                            Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.GENDER, t, dr("total"))
                    End Select
                Next


                'Dim DataAna As New Dictionary(Of mDB.Gender_Name.Type, Integer)
                'DataAna.Add(mDB.Gender_Name.Type.MALE, 0)
                'DataAna.Add(mDB.Gender_Name.Type.FEMALE, 0)

                'Dim g As mDB.Gender_Name.Type
                'For Each dr In dt.Rows
                '    g = dr("gender_type_id")
                '    If DataAna.ContainsKey(g) Then
                '        DataAna(g) = dr("Total")
                '    End If
                'Next

                'For Each d In DataAna
                '    Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.GENDER, d.Key, d.Value)
                'Next

            End Sub

#End Region

#Region "LANGUAGE"

            'Public Shared Sub SetLanguageAccounts()
            '    Dim db As mDB = mDB.GetDB

            '    Dim Accounts = db.VIEW.Account_UserEnabled.
            '    ToList()

            '    MyApp.WriteProcLog("BEGIN UPDATE LANGUAGE", TaskType.ELABORATE_DATA)

            '    For Each Acc In Accounts

            '        AnalysisFollowersLanguage(Acc)

            '    Next

            '    MyApp.WriteProcLog("END UPDATE LANGUAGE", TaskType.ELABORATE_DATA)
            '    MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)



            'End Sub
            Private Shared Sub AnalysisFollowersLanguage(Acc As mDB.Account)
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog(SF("(tab)(tab)update language follower analisys"), TaskType.ELABORATE_DATA)

                Dim dt = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info.
                    REL.Account_Add_Info.Language.
                    GroupBy("language.id").
                    SetSelect("language.id", "count(language.id) as Total").
                ToDataTable

                If dt.Rows.Count > 0 Then

                    For Each dr In dt.Rows
                        Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.LANGUAGE, dr("id"), dr("total"))
                    Next

                End If

            End Sub

#End Region

#Region "BUSINESS PROFILE"

            Public Shared Sub SetBusinessAccounts()
                Const MaxAccountUpdate = 5000
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE BUSINESS", TaskType.ELABORATE_DATA)

                For Each Acc In Accounts

                    Dim Accs = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        REL.Account.Account_Add_Info.
                        Where("business_type_id", "=", mDB.Account.BusinessType.NOT_ASSIGNED).
                        Limit(MaxAccountUpdate).
                    ToList(Of mDB.Account)()

                    If Accs.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update business type: {0}, number users: ({1})", Acc.ToString, Accs.Count), TaskType.ELABORATE_DATA)


                        For Each A In Accs

                            Dim coeff = A.CalculateActivityCoeff

                            If A.Account_Add_Info.Post_Hours_Total >= 200 Then
                                If coeff < 0.5 Then
                                    A.Account_Add_Info.Business_Type_Id = mDB.Account.BusinessType.BUSINESS
                                Else
                                    A.Account_Add_Info.Business_Type_Id = mDB.Account.BusinessType.PRIVATE
                                End If
                            Else
                                A.Account_Add_Info.Business_Type_Id = mDB.Account.BusinessType.UNKNOW
                            End If

                            db.SubmitChanges()

                        Next

                        'MyApp.WriteProcLog(SF("(tab)end update business type: {0}", Acc.Fullname), AutoProcType.ELABORATE_DATA)

                        'aggiorna l'analisi
                        'AnalysisFollowersBusiness(Acc)

                    End If


                Next

                MyApp.WriteProcLog("END UPDATE BUSINESS", TaskType.ELABORATE_DATA)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)



            End Sub
            Private Shared Sub AnalysisFollowersBusiness(Acc As mDB.Account)
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog(SF("(tab)(tab)update business follower analisys"), TaskType.ELABORATE_DATA)

                Dim dt = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info.
                    GroupBy("business_type_id").
                    SetSelect("business_type_id", "count(business_type_id) as Total").
                ToDataTable

                For Each dr In dt.Rows
                    Dim t As mDB.Account.BusinessType = dr("business_type_id")
                    Select Case t
                        Case mDB.Account.BusinessType.BUSINESS, mDB.Account.BusinessType.PRIVATE
                            Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.BUSINESS, t, dr("total"))
                    End Select

                Next

            End Sub

#End Region

#Region "STATUS"

            Public Shared Sub SetStatusAccounts()
                Const MaxAccountUpdate = 5000
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE STATUS", TaskType.ELABORATE_DATA)

                For Each Acc In Accounts

                    Dim FollAccs = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        REL.Account.Account_Add_Info.
                        Where("status_type_id", "=", mDB.Account.StatusType.NOT_ASSIGNED).
                        Limit(MaxAccountUpdate).
                    ToList(Of mDB.Account)()

                    If FollAccs.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update status type: {0}, number users: ({1})", Acc.ToString, FollAccs.Count), TaskType.ELABORATE_DATA)


                        For Each FollAcc In FollAccs

                            'controllo attività
                            Dim AccStatus As mDB.Account.StatusType = mDB.Account.StatusType.NOT_ASSIGNED

                            Dim postweek = FollAcc.Account_Add_Info.Post_Weeks

                            'se non ci sono dati li inserisco
                            If postweek.Count = 0 Then
                                Dim LastPosts =
                                    FollAcc._Tab_Account_Post.
                                    Where("pubb_date", ">", Date.UtcNow.AddDays(-(7 * 5))).
                                    SetSelect("pubb_date").
                                    Limit(50).ToList(Of Date)()

                                FollAcc.Account_Add_Info.Post_Weeks = FollAcc.UpdateWeekActivity(postweek, LastPosts)

                                MyApp.WriteProcLog(SF("(tab)(tab)init week post: {0}, posts: ({1})", FollAcc.ToString, LastPosts.Count), TaskType.ELABORATE_DATA)


                                'A.Account_Add_Info.Post_Weeks = postweek

                            End If


                            Dim weekmin = DateDiff(DateInterval.WeekOfYear, New Date(2000, 1, 1), Date.UtcNow, FirstDayOfWeek.Monday)
                            Dim Post4week = 0
                            For Each w In postweek
                                If CInt(w.Key) < weekmin And CInt(w.Key) > weekmin - 5 Then
                                    Post4week += w.Value
                                End If
                            Next

                            Select Case Post4week
                                Case 0
                                    AccStatus = mDB.Account.StatusType.INACTIVE
                                Case 1 To (1 * 4) '1
                                    AccStatus = mDB.Account.StatusType.LOW_ACTIVITY
                                Case (1 * 4) + 1 To (4 * 4) '2-4
                                    AccStatus = mDB.Account.StatusType.MEDIUM_ACTIVITY
                                Case Else '  5+
                                    AccStatus = mDB.Account.StatusType.HIGHT_ACTIVITY
                            End Select

                            'controllo fake
                            Dim FakeScore = 0
                            If FollAcc.Avatar.Contains("/default_profile_images/") Then
                                FakeScore += 8
                            End If
                            If FollAcc.Location.Trim = "" Then
                                FakeScore += 4
                            End If
                            If FollAcc.Description.Trim = "" Then
                                FakeScore += 4
                            End If
                            If FollAcc.Url.Trim = "" Then
                                FakeScore += 2
                            End If


                            If FollAcc.Account_Add_Info.Friend_Count < 10 Or FollAcc.Account_Add_Info.Follower_Count < 10 Then
                                FakeScore += 2
                            Else
                                Dim Rapp = Utils.Math.Div(FollAcc.Account_Add_Info.Friend_Count, FollAcc.Account_Add_Info.Follower_Count)

                                FakeScore += Math.Min(Math.Truncate(Rapp), 4)
                            End If

                            If Post4week <= 4 And FollAcc.Account_Add_Info.Post_Count < 20 Then
                                FakeScore += 2
                            End If

                            If FakeScore > 14 Then
                                AccStatus = mDB.Account.StatusType.FAKE
                            End If

                            MyApp.WriteProcLog(SF("(tab)(tab)update status: {0}, status: {1}, fakescore: {2}", FollAcc.ToString, AccStatus.ToString, FakeScore), TaskType.ELABORATE_DATA)

                            FollAcc.Account_Add_Info.Status_Type_Id = AccStatus

                            db.SubmitChanges()

                        Next

                        'MyApp.WriteProcLog(SF("(tab)end update status type: {0}", Acc.Fullname), AutoProcType.ELABORATE_DATA)

                        'aggiorna l'analisi
                        'AnalysisFollowersStatus(Acc)

                    End If


                Next

                MyApp.WriteProcLog("END UPDATE STATUS", TaskType.ELABORATE_DATA)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)



            End Sub
            Private Shared Sub AnalysisFollowersStatus(Acc As mDB.Account)
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog(SF("(tab)(tab)update status follower analisys"), TaskType.ELABORATE_DATA)

                Dim dt = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info.
                    GroupBy("status_type_id").
                    SetSelect("status_type_id", "count(status_type_id) as Total").
                ToDataTable

                For Each dr In dt.Rows
                    Dim t As mDB.Account.StatusType = dr("status_type_id")
                    Select Case t
                        Case mDB.Account.StatusType.NOT_ASSIGNED
                        Case Else
                            Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.STATUS, t, dr("total"))
                    End Select
                Next

            End Sub

#End Region

#Region "PLACE"

            Public Shared Sub AnalysisFollowersPlace(Acc As mDB.Account)
                Dim db As mDB = mDB.GetDB

                MyApp.WriteProcLog(SF("(tab)(tab)update place follower analisys"), TaskType.ELABORATE_DATA)


                Dim qCountryAccount = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info.
                    REL.Account_Add_Info.Place.
                    GroupBy("place.country_code").
                    SetSelect("place.country_code", "count(place.country_code) as tot")

                Dim qCountry = db.TAB.Place_Country

                Dim dt = db.GetQuery.
                    From(qCountryAccount, "country_accout", "").
                    Join(qCountry, "country_code", "country_accout.country_code", "country_place", "").
                    SetSelect("country_place.id", "country_accout.tot").
                ToDataTable()

                'prima rimetto tutto o 0
                'Acc.Tab_FollowerAnalysis(mDB.Follower_Analysis.Type.PLACE).
                '    Update.UpdateValue("value", 0).
                'ExecuteCommand()
                Acc.Tab_Follower_Analysis(mDB.Follower_Analysis.Type.PLACE).
                    Delete.
                ExecuteCommand()

                'inserisco i dati
                For Each dr As DataRow In dt.Rows
                    Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.PLACE, dr("id"), dr("tot"))
                Next



                ' Next
            End Sub

#End Region

#End Region

#Region "QUERY"

            Public Shared Sub CreateIndexQueryPosts(QueryId As Integer)

                Dim db As mDB = mDB.GetDB '(False) 'questo perchè viene utilizzata anche in async
                Dim query = db.TAB.Query.GetByPK(QueryId)

                Dim arc = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_QUERY, query.Id)

                'elimina l'indice
                arc.RemoveSimilTextArchiveData()

                Dim AD = arc.GetSimilTextArchiveData

                ' prende i primi 2000 post o che hanno me di 90 giorni
                'Dim Posts = db.
                '    TAB.Query_Post.
                '    BY.Query_Post.Query_Id(query.Id).
                '    Where("pubb_date", ">", Date.UtcNow.AddDays(-90)).
                '    OrderBy("pubb_date desc").
                '    Limit(2000).
                'ToList
                Dim Posts = query._Tab_Query_Post.
                    Where("pubb_date", ">", Date.UtcNow.AddDays(-90)).
                    OrderBy("pubb_date desc").
                    Limit(2000).
                ToList()


                Dim a = New SimilText.ArchiveText(AD)
                For Each p In Posts

                    a.Text = p.Post_Text
                    a.Id = p.Id
                    a.EditAttribute(query.Id, 0)
                    a.EditAttribute(Utils.Conv.ToTimeStamp(p.Pubb_Date), 1)
                    a.Archive()

                Next
                a.Close()
                a = Nothing

                query.Post_Count = Posts.Count
                query.Last_Update = Date.UtcNow
                db.SubmitChanges()

                'una volta indicizzato cancello dall ultimo in poi
                If Posts.Count > 0 Then
                    query._Tab_Query_Post.
                        Where("pubb_date", "<", Posts.Last.Pubb_Date).
                    Delete.ExecuteCommand()
                End If

                Posts = Nothing
                query = Nothing

            End Sub

#End Region

#Region "ARCHIVE TEXT"

            Public Shared Sub CreateIndexFollowersPosts(Excecute As Boolean)
                Dim db As mDB = mDB.GetDB

                If Excecute Then
                    MyApp.WriteProcLog("BEGIN INDEX FOLLOWERS POST", TaskType.INDEX_DATA)

                    'trova tutti gli account da agiornare i post
                    Dim Accs = db.VIEW.Account_UserAnalysisFollowers.
                        REL.Account.Account_Update.
                        BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                        Where("Analysis_Follower_Post_Update", "<", Date.UtcNow.AddDays(-7)).
                    ToList()

                    For Each Acc In Accs

                        'verifica che siano stati agiornati i post dei followers che hanno almenno un post
                        'Dim pp = db.TAB.Account.
                        '    REL.Account.Account_Update.
                        '    REL.Account.Account_Link.
                        '    BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                        '    Where("post_update", "<", Date.MinValue).
                        '    Where("post_update_count", ">", 0).
                        '    Limit(1).
                        'ToList()

                        Dim pp = Acc._Tab_Account_Link_Analysis(True).
                            REL._Account_Link.Account_Add_Info.
                            Where("post_update", "<", Date.MinValue).
                            Where("post_update_count", ">", 0).
                            Limit(1).
                        ToList()


                        If pp.Count = 0 Then

                            CreateIndexFollowersPostsAccount(Acc.Id)

                            Acc.Account_Update.Analysis_Follower_Post_Update = Date.UtcNow
                            db.SubmitChanges()
                        Else
                            MyApp.WriteProcLog(SF("(tab)NO index follower account:{0}, error account: {1}", Acc.Fullname, pp(0).Account_Link_Id), TaskType.INDEX_DATA)

                        End If

                    Next

                    MyApp.WriteProcLog("END INDEX FOLLOWERS POST", TaskType.INDEX_DATA)

                End If

            End Sub
            Public Shared Sub CreateIndexFollowersPostsAccount(AccountID As Integer)
                Const MaxFollowerIndex = 15000
                Const MaxPostIdexPerFoll = 400
                Dim db As mDB = mDB.GetDB '(False) 'questo perchè viene utilizzata anche in async


                Dim Acc = db.TAB.Account.GetByPK(AccountID)
                Dim ArchiveDB = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_FOLLOWERS, Acc.Id)

                ArchiveDB.RemoveSimilTextArchiveData()

                Dim AD = ArchiveDB.GetSimilTextArchiveData

                'Dim Folls = db.TAB.Account.
                '    REL.Account.Account_Link.
                '    BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                '    Limit(MaxFollowerIndex).
                'ToList

                Dim Folls = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                    REL._Account_Link.Account.
                    Limit(MaxFollowerIndex).
                ToList(Of mDB.Account)()

                Dim CtFoll As Integer = 0

                Dim AnHours(23) As Integer

                Dim ArcText = New SimilText.ArchiveText(AD)

                MyApp.WriteProcLog(SF("(tab)begin index follower account:{0}, Followers: {1}", Acc.Fullname, Folls.Count), TaskType.INDEX_DATA)

                For Each f In Folls

                    Dim Posts = f._Tab_Account_Post.
                        Where("pubb_date", ">", Date.UtcNow.AddDays(-90)).
                        OrderBy("pubb_date desc").
                        Limit(MaxPostIdexPerFoll).
                    ToList

                    CtFoll += 1
                    MyApp.WriteProcLog(SF("(tab)(tab)Follower {0} di {1}, post: {2}", CtFoll, Folls.Count, Posts.Count), TaskType.INDEX_DATA)

                    For Each p In Posts

                        ArcText.Text = p.Post_Text
                        ArcText.Id = p.Id
                        ArcText.EditAttribute(p.Account_Id, 0)
                        ArcText.EditAttribute(Utils.Conv.ToTimeStamp(p.Pubb_Date), 1)
                        ArcText.Archive()

                        'AnHours(p.Pubb_Date.Hour) += 1
                        AnHours(Acc.LDate(p.Pubb_Date).Hour) += 1

                        p = Nothing

                    Next


                    'una volta indicizzato cancello dall ultimo in poi
                    If Posts.Count > 0 Then
                        f._Tab_Account_Post.
                            Where("pubb_date", "<", Posts.Last.Pubb_Date).
                        Delete.ExecuteCommand()
                    End If

                    Posts = Nothing

                Next

                ArcText.Close()
                ArcText = Nothing

                '----------------------------------------------------------
                'crea analisi per ora followers inserisco i dati

                For ct = 0 To AnHours.Length - 1
                    Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.HOURS_ACTIVITY, ct, AnHours(ct))
                Next

            End Sub
            Public Shared Sub CreateIndexProfilePosts(ProfID As Integer)
                Dim db As mDB = mDB.GetDB '(False) 'questo perchè viene utilizzata anche in async

                Dim Prof = db.TAB.Profile.GetByPK(ProfID)
                Dim Acc = Prof.Account
                Dim arc = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_ACCOUNT, Prof.Id)

                arc.RemoveSimilTextArchiveData()

                Dim AD = arc.GetSimilTextArchiveData

                Dim a = New SimilText.ArchiveText(AD)

                Dim Posts = Acc._Tab_Account_Post.
                    Where("pubb_date", ">", Date.UtcNow.AddDays(-180)).
                    OrderBy("pubb_date desc").
                    Limit(4000).
                ToList

                MyApp.WriteProcLog(SF("(tab)begin index post account:{0}, Posts: {1}", Acc.ToString, Posts.Count), TaskType.INDEX_DATA)
                Dim PostCount = 0
                For Each p In Posts

                    If Not p.Post_Text.StartsWith("RT ") Then
                        a.Text = p.Post_Text
                        a.Id = p.Id
                        a.EditAttribute(p.Account_Id, 0)
                        a.EditAttribute(Utils.Conv.ToTimeStamp(p.Pubb_Date), 1)
                        a.Archive()

                        PostCount += 1
                    End If

                    p = Nothing

                Next

                'aggiorno DB
                Prof.Post_Count = PostCount
                Prof.Post_Download_Count = PostCount
                Prof.Last_Update = Date.UtcNow
                db.SubmitChanges()

                'una volta indicizzato cancello dall ultimo in poi
                If Posts.Count > 0 Then
                    Acc._Tab_Account_Post.
                        Where("pubb_date", "<", Posts.Last.Pubb_Date).
                    Delete.ExecuteCommand()

                End If


                a.Close()
                a = Nothing
                Posts = Nothing

            End Sub


            'Public Shared Sub CreateIndexFollowersPostsAccount(AccountID As Integer)
            '    Dim db As mDB = mDB.GetDB(False) 'questo perchè viene utilizzata anche in async

            '    Dim Acc = db.TAB.Account.GetByPK(AccountID)
            '    Dim arc = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_FOLLOWERS, Acc.Id)

            '    arc.RemoveSimilTextArchiveData()

            '    Dim AD = arc.GetSimilTextArchiveData

            '    Dim Folls = db.TAB.Account.REL.Account.Account_Link.BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
            '        ToList

            '    Dim dt_Post As DataTable
            '    Dim p As DataRow
            '    Dim CtFoll As Integer = 0

            '    Dim AnHours As New Dictionary(Of Integer, Integer)
            '    For ct = 0 To 23
            '        AnHours.Add(ct, 0)
            '    Next

            '    Dim a = New SimilText.ArchiveText(AD)

            '    MyApp.WriteProcLog(SF("(tab)begin index follower account:{0}, Followers: {1}", Acc.Fullname, Folls.Count), AutoProcType.ELABORATE_DATA)

            '    For Each f In Folls

            '        dt_Post = f._Tab_Account_Post.
            '            Where("pubb_date", ">", Date.UtcNow.AddDays(-90)).
            '            OrderBy("pubb_date desc").
            '            Limit(400).
            '        ToDataTable()

            '        CtFoll += 1
            '        MyApp.WriteProcLog(SF("(tab)(tab)Follower {0} di {1}, post: {2}", CtFoll, Folls.Count, dt_Post.Rows.Count), AutoProcType.ELABORATE_DATA)

            '        For ctres = 0 To dt_Post.Rows.Count - 1
            '            p = dt_Post.Rows(ctres)

            '            a.Text = p("Post_Text")
            '            a.Id = p("Id")
            '            a.EditAttribute(p("Account_Id"), 0)
            '            a.EditAttribute(Utils.Conv.ToTimeStamp(p("Pubb_Date").value), 1)
            '            a.Archive()

            '            AnHours(p("Pubb_Date").value.Hour) += 1

            '            p = Nothing

            '        Next

            '        dt_Post = Nothing

            '        ''una volta indicizzato cancello dall ultimo in poi
            '        'If Posts.Count > 0 Then
            '        '    f._Tab_Account_Post.
            '        '        Where("pubb_date", "<", dt_Post.Rows.Las.Pubb_Date).
            '        '    Delete.ExecuteCommand())
            '        'End If

            '    Next

            '    a.Close()
            '    a = Nothing


            '    'crea analisi per ora followers
            '    'inserisco i dati

            '    For Each d In AnHours
            '        Acc.SetFollowerAnalysis(mDB.Follower_Analysis.Type.HOURS_ACTIVITY, d.Key, d.Value)
            '    Next


            'End Sub
#End Region

#Region "CATEGORIZE"

            Public Shared Sub CategorizeFollowers(Excecute As Boolean)

                Dim db As mDB = mDB.GetDB

                If Excecute Then
                    MyApp.WriteProcLog("BEGIN CATEGORIZE FOLLOWERS ", TaskType.INDEX_DATA)

                    'trova tutti gli account da agiornare i post
                    Dim Accs = db.VIEW.Account_UserAnalysisFollowers.
                        REL.Account.Account_Update.
                        BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                        Where("Analysis_Follower_Post_Update", ">", Date.UtcNow.AddDays(-30)).
                    ToList()

                    'BY.Account.Id(588).
                    For Each Acc In Accs

                        CategorizeFollowersAccount(Acc.Id)

                    Next

                    MyApp.WriteProcLog("END CATEGORIZE FOLLOWERS ", TaskType.INDEX_DATA)

                End If

            End Sub
            Public Shared Sub CategorizeFollowersAccount(AccountID As Integer)
                Dim db As mDB = mDB.GetDB

                Dim Acc = db.TAB.Account.GetByPK(AccountID)
                Dim FollCats = Acc.Tab_Categorize_Follower.
                    Where("categorize_update", "<", Acc.Account_Update.Analysis_Follower_Post_Update).
                ToList()

                If FollCats.Count > 0 Then

                    MyApp.WriteProcLog(SF("(tab)begin analysis follower account: {0}, categorie: {1}", Acc.ToString, FollCats.Count), TaskType.INDEX_DATA)

                    For Each FollCat In FollCats

                        Dim t = Date.UtcNow.Ticks

                        CategorizeFollowersAccountCategory(FollCat)

                    Next

                End If

            End Sub
            Public Shared Sub CategorizeFollowersAccountCategory(FollCat As mDB.Categorize_Follower)
                Dim db As mDB = mDB.GetDB


                Dim t = Date.UtcNow.Ticks

                Dim Cat = db.TAB.Categorize.GetByPK(FollCat.Categorize_Id)

                If Cat Is Nothing Then

                    MyApp.WriteProcLog(SF("(tab)(tab)categorie non exist"), TaskType.ELABORATE_DATA)

                    FollCat.Accuracy_Total_Account = -1
                    FollCat.Account_Count = -1
                    FollCat.Categorize_Update = Date.UtcNow

                Else

                    Dim AD = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_FOLLOWERS, FollCat.Account_Id).GetSimilTextArchiveData
                    Dim f As New SimilText.FindSimilarText(AD)

                    f.Text = Cat.Query
                    f.RankMin = 70 ' Utils.Conv.ToInt(Me.TxtAcc.Text)
                    f.Find()
                    f.Close()

                    '----------------------------------------------------------
                    ' TROVA GLI ACCOUNT CON MAGGIOR ACCURACY
                    '----------------------------------------------------------
                    Dim AccuracyAcc = FollCat.Accuracy_Total_Account
                    If AccuracyAcc = 0 Then AccuracyAcc = 1000

                    Dim Accounts = (
                        From r In f.Result.Matches
                        Group r By r.Attribute0 Into g = Group
                        Select id = Attribute0, AccTot = g.Sum(Function(o) o.Accuracy), PostTotal = g.Count
                        Where AccTot >= AccuracyAcc
                    ).ToList

                    'elimino la lista precedende
                    'db.TAB.Categorize_Account.BY.Categorize_Account.Categorize_Follower_Id(AccList.Id).Delete.ExecuteCommand()
                    db.TAB.Categorize_Account.BY.Categorize_Account.Account_Id(FollCat.Account_Id, Cat.Id).Delete.ExecuteCommand()

                    'inserisco gli account nel db
                    db.InitMultiRowsInsert()
                    For Each a In Accounts
                        db.InsertRowOnSubmit(New mDB.Categorize_Account With {
                            .Account_Id = FollCat.Account_Id,
                            .Categorize_Id = Cat.Id,
                            .Account_Categozie_Id = a.id,
                            .Post_Total = a.PostTotal,
                            .Accuracy = a.AccTot
                        })
                    Next
                    db.SubmitChanges()

                    MyApp.WriteProcLog(SF("(tab)(tab)categorie: {3}, founds: {0} foll, tot time: {1}, analysis time: {2}", Accounts.Count, (Now.Ticks - t) / 10000000, f.Result.ExecTime, Cat.Description), TaskType.ELABORATE_DATA)

                    FollCat.Accuracy_Total_Account = AccuracyAcc
                    FollCat.Account_Count = Accounts.Count
                    FollCat.Categorize_Update = Date.UtcNow
                End If


                db.SubmitChanges()


            End Sub

            'Public Shared Sub CategorizeFollowersAccount(AccountID As Integer)
            '    Dim db As mDB = mDB.GetDB

            '    Dim Acc = db.TAB.Account.GetByPK(AccountID)
            '    Dim FollCats = Acc.Tab_Categorize_Follower.
            '        Where("prefered", "=", True).
            '        Where("categorize_update", "<", Acc.Account_Update.Analysis_Follower_Update_Date).
            '    ToList()


            '    MyApp.WriteProcLog(SF("(tab)begin analysis follower account: {0}, categorie: {1}", Acc.Fullname, FollCats.Count), AutoProcType.ELABORATE_DATA)

            '    For Each FollCat In FollCats

            '        Dim t = Date.UtcNow.Ticks

            '        Dim Cat = db.TAB.Categorize.GetByPK(FollCat.Categorize_Id)
            '        Dim AD = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_FOLLOWERS, Acc.Id).GetSimilTextArchiveData
            '        Dim f As New SimilText.FindSimilarText(AD)

            '        f.Text = Cat.Query
            '        f.RankMin = 70 ' Utils.Conv.ToInt(Me.TxtAcc.Text)
            '        f.Find()
            '        f.Close()

            '        '----------------------------------------------------------
            '        ' TROVA GLI ACCOUNT CON MAGGIOR ACCURACY
            '        '----------------------------------------------------------
            '        Dim AccuracyAcc = FollCat.Accuracy_Total_Account
            '        If AccuracyAcc = 0 Then AccuracyAcc = 1000

            '        Dim Accounts = (
            '            From r In f.Result.Matches
            '            Group r By r.Attribute0 Into g = Group
            '            Select id = Attribute0, AccTot = g.Sum(Function(o) o.Accuracy), PostTotal = g.Count
            '            Where AccTot >= AccuracyAcc
            '        ).ToList

            '        'elimino la lista precedende
            '        'db.TAB.Categorize_Account.BY.Categorize_Account.Categorize_Follower_Id(AccList.Id).Delete.ExecuteCommand()
            '        db.TAB.Categorize_Account.BY.Categorize_Account.Account_Id(Acc.Id, Cat.Id).Delete.ExecuteCommand()

            '        'inserisco gli account nel db
            '        db.InitMultiRowsInsert()
            '        For Each a In Accounts
            '            db.InsertRowOnSubmit(New mDB.Categorize_Account With {
            '                .Account_Id = Acc.Id,
            '                .Categorize_Id = Cat.Id,
            '                .Account_Categozie_It = a.id,
            '                .Post_Total = a.PostTotal,
            '                .Accuracy = a.AccTot
            '            })
            '        Next
            '        db.SubmitChanges()

            '        MyApp.WriteProcLog(SF("(tab)(tab)categorie: {3}, founds: {0} foll, tot time: {1}, analysis time: {2}", Accounts.Count, (Now.Ticks - t) / 10000000, f.Result.ExecTime, Cat.Description), AutoProcType.ELABORATE_DATA)

            '        FollCat.Account_Count = Accounts.Count
            '        FollCat.Categorize_Update = Date.UtcNow
            '        db.SubmitChanges()

            '    Next


            'End Sub

#End Region

#Region "AUTO FOLLOW"

            Public Shared Sub CheckFriendToFollower()
                'controlla se ci sono dei friends sono diventati followre
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN BECOME FOLLOWER ACCOUNT", TaskType.AUTO_FOLLOW)

                For Each Acc In Accounts
                    'Dim follacc = Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.FOLLOW).
                    '    REL.Auto_Follow_Account.Account_Code.
                    '    REL.Account.Account_Link.
                    '    BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                    'ToList

                    Dim follacc = Acc._Tab_Account_Link(GloukDB._Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        REL.Account.Auto_Follow_Account_to_foll.
                        BY.Auto_Follow_Account.Account_Id(Acc.Id, GloukDB.Auto_Follow_Account.StatusType.FOLLOW).
                    ToList(Of mDB.Auto_Follow_Account)()

                    If follacc.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)become follow : {0}, follower number: {1}", Acc.Fullname, follacc.Count), TaskType.AUTO_FOLLOW)

                        For Each f In follacc
                            f.Status_Id = mDB.Auto_Follow_Account.StatusType.BECOME_FOLLOWER
                            f.Update_Status_Date = Date.UtcNow
                            db.SubmitChanges()

                            MyApp.WriteProcLog(SF("(tab)(tab)follower: [{0}]", f.Account_To_Foll_Id), TaskType.AUTO_FOLLOW)

                        Next

                    End If


                Next

                MyApp.WriteProcLog("END BECOME FOLLOWER ACCOUNT", TaskType.AUTO_FOLLOW)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.AUTO_FOLLOW)

            End Sub
            Public Shared Sub AddFollowAccountFromQuery()
                Const MaxAccountForQuery = 50
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE AUTO FOLLOW QUERY", TaskType.AUTO_FOLLOW)

                For Each Acc In Accounts

                    Dim FollQuery = Acc.Tab_Auto_Follow_Query.
                        Where("followed_update", "<", Date.UtcNow.AddHours(-12)).
                    ToList


                    If FollQuery.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update auto follow query: {0}, number query: ({1})", Acc.ToString, FollQuery.Count), TaskType.AUTO_FOLLOW)

                        For Each q In FollQuery

                            'TODO verifica se i pendig di una singola query sono + 3 giorni
                            'verifica se i pendig di un profilo singolo + di 4 giorni
                            Dim PendingCount = Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.PENDING).
                                Where("Source_Type_Id", "=", mDB.Auto_Follow_Account.SourceType.QUERY).
                                Where("Source_Id", "=", q.Query_Id).
                                SetSelect("Count(*)").
                            ToObj(Of Integer)()

                            Dim Query = db.TAB.Query.GetByPK(q.Query_Id)

                            If PendingCount > MaxAccountForQuery * 4 Then

                                MyApp.WriteProcLog(SF("(tab)(tab)too many follower pending query: {0}, account: ({1})", Query.ToString, PendingCount), TaskType.AUTO_FOLLOW)

                                q.Followed_Update = Date.UtcNow.AddDays(2)
                                db.SubmitChanges()

                            Else

                                '----------------------------------------------------------------
                                'cerca account che hano almeno un certo accuracy

                                Dim AD = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_QUERY, Query.Id).GetSimilTextArchiveData
                                Dim f As New SimilText.FindSimilarText(AD)

                                f.Text = Query.Query
                                f.RankMin = 1
                                f.Find()
                                f.Close()

                                ' accuracy min per account
                                Dim AccuracyAccount As Integer = q.Accuracy_Total_Account
                                If AccuracyAccount = 0 Then
                                    AccuracyAccount = AD.Rank_Hashtag_hashtag * 4
                                End If

                                If f.Result.Matches.Count > 0 Then

                                    'post collegati con i risultati
                                    Dim ids = (From r In f.Result.Matches Select r.Id).ToList
                                    Dim posts = Query._Tab_Query_Post.Where("id", "IN", ids).ToList
                                    Dim PostFind = (
                                        From r In f.Result.Matches
                                        Join p In posts On r.Id Equals p.Id
                                        Select Post = p, Res = r
                                    ).ToList

                                    'account trovati con un accuracy maggiore di tot
                                    Dim AccFind = (
                                        From p In PostFind
                                        Group p By p.Post.Account_Code, p.Post.Account_Username Into g = Group
                                        Select Account_Code, Account_Username, AccTot = g.Sum(Function(o) o.Res.Accuracy), post_count = g.Count
                                        Where AccTot >= AccuracyAccount Order By AccTot Descending
                                    ).ToList


                                    If AccFind.Count > 0 Then
                                        Dim Accountinsert = 0

                                        MyApp.WriteProcLog(SF("(tab)(tab)add follow account from query: {0}, number account: ({1})", Query.ToString, AccFind.Count), TaskType.AUTO_FOLLOW)

                                        'inserisco comeaccount da seguire
                                        For Each dr In AccFind

                                            Dim NewAcc = mDB.Account.GetForUpdate(dr.Account_Code, Network.AccType.TWITTER_ACCOUNT)

                                            Dim CountFoll As Integer
                                            'IMPORTANTE inserisce un account da seguire anche se esiste già e non viene toccato da da almeno 6 mesi
                                            If Acc.CheckAddAutoFollAccount(NewAcc.Id, CountFoll) Then
                                                Accountinsert += 1
                                                MyApp.WriteProcLog(SF("(tab)(tab)(tab)add follow account: {0}, number post: ({1}), gia inserito: ({2})", dr.Account_Username, dr.post_count, CountFoll), TaskType.AUTO_FOLLOW)

                                                Dim FollAcc = New mDB.Auto_Follow_Account With {
                                                    .Account_Id = Acc.Id,
                                                    .Account_To_Foll_Id = NewAcc.Id,
                                                    .Count_Follow = CountFoll + 1,
                                                    .Status_Id = mDB.Auto_Follow_Account.StatusType.PENDING,
                                                    .Update_Status_Date = Date.UtcNow,
                                                    .Source_Type_Id = mDB.Auto_Follow_Account.SourceType.QUERY,
                                                    .Source_Id = q.Query_Id,
                                                    .Source_Description = SF("{0} ({1})", Query.Query, Query.Lang_Code)
                                                }

                                                db.TAB.Auto_Follow_Account.InsertOnSubmit(FollAcc)
                                                db.SubmitChanges()
                                            End If

                                            ' se ci sono troppi account da inserire si ferma
                                            If Accountinsert >= MaxAccountForQuery Then
                                                MyApp.WriteProcLog(SF("(tab)(tab)stop add follow account"), TaskType.AUTO_FOLLOW)
                                                Exit For
                                            End If
                                        Next

                                    End If

                                End If

                                q.Followed_Update = Date.UtcNow

                            End If

                            db.SubmitChanges()

                        Next

                        MyApp.WriteProcLog(SF("(tab)end update auto follow query: {0}", Acc.Fullname), TaskType.AUTO_FOLLOW)

                        ' IMPORTANTE
                        'aggiorna gli account dei follower
                        Update.AccountAccountsUpdate(New List(Of mDB.Account) From {Acc}, GloukDB.Account.UpdateAccountMode.AUTO_FOLLOW)

                    End If

                Next

                MyApp.WriteProcLog("END UPDATE AUTO FOLLOW QUERY", TaskType.AUTO_FOLLOW)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.AUTO_FOLLOW)

            End Sub

            Public Shared Sub AddUnFollowNotFollower()
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                    REL.Account.Account_Option.
                    Where("auto_unfoll_not_follower", "=", True).
                    Where("auto_unfoll_not_follower_update", "<", Date.UtcNow.AddDays(-1)).
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE UNFOLLOW NOT FOLLOWER", TaskType.AUTO_FOLLOW)


                For Each Acc In Accounts

                    ' IMPORTANTE prendo solo quelli che seguo da + di un mese
                    Dim qFriend = Acc._Tab_Account_Link(mDB._Account_Link.Type.FRIENDS).
                        REL._Account_Link.Account.
                        Where("create_date", "<", Date.UtcNow.AddMonths(-1)).
                        SetSelect("account_link_id", "account_code")

                    Dim qFollower = Acc._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER).
                        SetSelect("account_link_id")

                    Dim AccIds = db.GetQuery.From(qFriend, "Friend", "").
                        JoinLeft(qFollower, "account_link_id", "Friend.account_link_id", "Follower", "").
                        Where("Follower.account_link_id", "is null").
                        SetSelect("Friend.account_code").
                        Limit(50).
                    ToList(Of Integer)()

                    If AccIds.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin unfollow: {0}, number profile: ({1})", Acc.ToString, AccIds.Count), TaskType.AUTO_FOLLOW)

                        For Each AccID In AccIds
                            Dim FollAcc = db.TAB.Auto_Follow_Account.BY.Auto_Follow_Account.Account_Id(Acc.Id, AccID).ToObj

                            Dim DbUpdate = False
                            If FollAcc Is Nothing Then

                                DbUpdate = True

                                FollAcc = New mDB.Auto_Follow_Account With {
                                    .Account_Id = Acc.Id,
                                    .Account_To_Foll_Id  = Accid
                                }

                                db.TAB.Auto_Follow_Account.InsertOnSubmit(FollAcc)

                                MyApp.WriteProcLog(SF("(tab)(tab)(tab)add unfollow account: [{0}]", AccID), TaskType.AUTO_FOLLOW)

                            Else

                                If FollAcc.Update_Status_Date < Date.UtcNow.AddMonths(-1) Then
                                    DbUpdate = True
                                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)update unfollow account: [{0}]", AccID), TaskType.AUTO_FOLLOW)

                                End If

                            End If

                            If DbUpdate Then

                                FollAcc.Status_Id = mDB.Auto_Follow_Account.StatusType.FOLLOW
                                FollAcc.Update_Status_Date = Date.UtcNow
                                FollAcc.Follow_Date = Date.UtcNow.AddMonths(-1)
                                FollAcc.Source_Type_Id = mDB.Auto_Follow_Account.SourceType.UNFOLL_NO_FOLLOWER
                                FollAcc.Source_Id = 0


                            End If

                            db.SubmitChanges()

                        Next

                        Acc.Account_Option.Auto_Unfoll_Not_Follower_Update = Date.UtcNow
                        db.SubmitChanges()

                    End If

                Next

                MyApp.WriteProcLog("END UPDATE UNFOLLOW NOT FOLLOWER", TaskType.AUTO_FOLLOW)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.AUTO_FOLLOW)


            End Sub


            Public Shared Sub AddFollowAccountFromFollowerProfile()
                Const MaxAccountForProfile = 50
                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN UPDATE FOLLOW FROM FOLLOWER PROFILE", TaskType.AUTO_FOLLOW)

                For Each Acc In Accounts

                    Dim FollProfiles = Acc.Tab_Auto_Follow_Profile.
                        Where("followed_update", "<", Date.UtcNow.AddHours(-12)).
                    ToList


                    If FollProfiles.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin update follow profile: {0}, number profile: ({1})", Acc.ToString, FollProfiles.Count), TaskType.AUTO_FOLLOW)

                        'scorre i profili di cui seguire gli follower
                        For Each FollProf In FollProfiles


                            'verifica se i pendig di un profilo singolo + di 4 giorni
                            Dim PendingCount = Acc.Tab_Auto_Follow_Account(mDB.Auto_Follow_Account.StatusType.PENDING).
                                Where("Source_Type_Id", "=", mDB.Auto_Follow_Account.SourceType.PROFILE_FOLLOWER).
                                Where("Source_Id", "=", FollProf.Profile_Account_Id).
                                SetSelect("Count(*)").
                            ToObj(Of Integer)()

                            Dim AccProfile = db.TAB.Account.GetByPK(FollProf.Profile_Account_Id)

                            If PendingCount > MaxAccountForProfile * 4 Then
                                MyApp.WriteProcLog(SF("(tab)(tab)too many follow pending from account: {0}, number account: ({1})", AccProfile.ToString, PendingCount), TaskType.AUTO_FOLLOW)

                                FollProf.Followed_Update = Date.UtcNow.AddDays(2)

                            Else

                                Dim tw = New WebApi.Twitter.TwitterClient(Acc.GetOauth)

                                Dim Accountinsert = 0
                                Dim AccountDownload = 0

                                'inserimento account follower del profilo
                                Do

                                    Dim Page = "-1"

                                    If FollProf.Follower_Last_Code <> "" Then
                                        Page = FollProf.Follower_Last_Code
                                    End If

                                    Dim AccCodes = tw.GetFollowers("", AccProfile.Account_Code, Page, MaxAccountForProfile * 10)
                                    AccountDownload += AccCodes.ids.Count

                                    'If False Then
                                    '    Dim uu = tw.GetUsersLookup("", String.Join(",", AccCodes.ids))
                                    '    uu = (From u In uu Where u.lang = "it").ToList
                                    '    AccCodes.ids = uu.Select(Function(o) o.id_str).ToList
                                    'End If

                                    If AccCodes.ids.Count > 0 Then

                                        MyApp.WriteProcLog(SF("(tab)(tab)add follow account from profile: {0}, followers: ({1}), number account: ({2})", AccProfile.ToString, AccProfile.Account_Add_Info.Follower_Count, AccCodes.ids.Count), TaskType.AUTO_FOLLOW)

                                        'inserisco account da seguire
                                        For Each AccCode In AccCodes.ids

                                            Dim NewAcc = mDB.Account.GetForUpdate(AccCode, Network.AccType.TWITTER_ACCOUNT)

                                            Dim CountFoll As Integer
                                            'IMPORTANTE inserisce un account da seguire anche se esiste già e non viene toccato da da almeno 6 mesi
                                            If Acc.CheckAddAutoFollAccount(NewAcc.Id, CountFoll) Then
                                                Accountinsert += 1
                                                MyApp.WriteProcLog(SF("(tab)(tab)(tab)add follow account: '{0}', gia inserito: ({1})", AccCode, CountFoll), TaskType.AUTO_FOLLOW)

                                                Dim FollAcc = New mDB.Auto_Follow_Account With {
                                                    .Account_Id = Acc.Id,
                                                    .Account_To_Foll_Id = NewAcc.Id,
                                                    .Count_Follow = CountFoll + 1,
                                                    .Status_Id = mDB.Auto_Follow_Account.StatusType.PENDING,
                                                    .Update_Status_Date = Date.UtcNow,
                                                    .Source_Type_Id = mDB.Auto_Follow_Account.SourceType.PROFILE_FOLLOWER,
                                                    .Source_Id = AccProfile.Id,
                                                    .Source_Description = "@" & AccProfile.Username
                                                }

                                                db.TAB.Auto_Follow_Account.InsertOnSubmit(FollAcc)
                                                db.SubmitChanges()

                                            End If

                                        Next
                                    Else

                                        MyApp.WriteProcLog(SF("(tab)(tab)finish follow account from profile: {0}", AccProfile.ToString), TaskType.AUTO_FOLLOW)

                                    End If

                                    'salviamo il cursore di dove siamo arrivati
                                    FollProf.Follower_Last_Code = AccCodes.next_cursor_str
                                    db.SubmitChanges()

                                    'se abbiamo finito i follower usciamo
                                    If FollProf.Follower_Last_Code = "0" Then
                                        Exit Do
                                    End If

                                Loop Until (Accountinsert >= MaxAccountForProfile) Or (AccountDownload >= MaxAccountForProfile * 100)


                                'se abbiamo finito i follower ricominciamo ma spostiamo la data in avanti di un mese
                                If FollProf.Follower_Last_Code = "0" Then
                                    FollProf.Follower_Last_Code = ""
                                    FollProf.Followed_Update = Date.UtcNow.AddMonths(1)
                                    MyApp.WriteProcLog(SF("(tab)(tab)finish follower account: {0}", AccProfile.ToString), TaskType.AUTO_FOLLOW)

                                Else
                                    FollProf.Followed_Update = Date.UtcNow
                                End If

                            End If

                            db.SubmitChanges()

                        Next

                        ' IMPORTANTE
                        'aggiorna gli account dei follower
                        Update.AccountAccountsUpdate(New List(Of mDB.Account) From {Acc}, GloukDB.Account.UpdateAccountMode.AUTO_FOLLOW)

                    End If

                Next


                MyApp.WriteProcLog("END UPDATE FOLLOW FROM FOLLOWER PROFILE", TaskType.AUTO_FOLLOW)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.AUTO_FOLLOW)

            End Sub

#End Region

#Region "SHARE POST"

            Public Shared Sub AddSharedPostsToTask()
                Dim db As mDB = mDB.GetDB


                'AddPostShareToTask
                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN SHARE POST FOR TASK", TaskType.UPDATE_POSTS)

                For Each Acc In Accounts

                    'trova tutti gli followers da agiornare i post
                    Dim Tasks =
                        db.TAB.Account.
                        REL.Account.Account_Add_Info.
                        REL.Account.Task_Send.
                        BY.Task_Send.Account_Id(Acc.Id).
                        Where("task_send.expired_task", "=", False).
                        Where("task_send.enabled_task", "=", True).
                        Where("share_update_post_count <> post_update_count").
                        Where("task_send.share_update", "<", Date.UtcNow.AddHours(-1)).
                        SetSelect("task_send.*").
                    ToList(Of mDB.Task_Send)()

                    If Tasks.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin share post : {0}, account number: {1}", Acc.ToString, Tasks.Count), TaskType.UPDATE_POSTS)

                        'tw.oauth = Acc.getOauth

                        For Each t In Tasks
                            'Dim LastPost = tw.SendShareAccountPost(al.Account_Link_Id, al.Update_Str)
                            AddAccountPostsToTask(t)


                        Next

                    End If


                Next

                MyApp.WriteProcLog("END SHARE POST", TaskType.UPDATE_POSTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_POSTS)


            End Sub
            Private Shared Sub AddAccountPostsToTask(task As mDB.Task_Send)
                Dim db As mDB = mDB.GetDB
                Dim MaxPost = 10

                ' trova la data dell ultimo post condiviso
                Dim LastDate As Date = Date.MinValue
                If task.Share_Update_Post_Code <> "" Then
                    Dim LastPost = task.Share_Account._Tab_Account_Post.BY._Account_Post._Post_Code(task.Share_Update_Post_Code).ToObj
                    If LastPost IsNot Nothing Then
                        LastDate = LastPost.Pubb_Date
                    End If
                End If

                'prendo i post + nuovi rispetto all'ultimo e che sia diverso dall' ultimo
                Dim SharePosts = task.Share_Account._Tab_Account_Post.
                    Where("Pubb_Date", ">=", LastDate).
                    Where("Post_Code", "<>", task.Share_Update_Post_Code).
                    OrderBy("Pubb_Date desc").
                    Limit(MaxPost).
                ToList()

                'IMPORTANTE tolgo i post condivisi
                SharePosts = (From p In SharePosts Where Not p.Post_Text.StartsWith("RT ")).ToList

                ' se esistono post
                If SharePosts.Count > 0 Then
                    MyApp.WriteProcLog(SF("(tab)(tab)begin share post account : {0}, post number: {1}", task.Share_Account_Id, SharePosts.Count), TaskType.UPDATE_POSTS)

                    ' se non li condivide tutti cancello quelli che eventualmente ci sono ancora da spedire e ne aggiungo solo 1
                    If Not task.Share_All_Post Then
                        task.Tab_Task_Post.Where("send_post", "=", False).Delete.ExecuteCommand()
                    End If

                    For Each p In SharePosts

                        MyApp.WriteProcLog(SF("(tab)(tab)(tab)share post code: {0}", p.Post_Code), TaskType.UPDATE_POSTS)

                        Dim Post = New mDB.Task_Post With {
                            .Task_Send_Id = task.Id,
                            .Post_Text = p.Post_Text,
                            .Post_Type_Id = mDB.Task_Post.Type.SHARE,
                            .Share_Post_Code = p.Post_Code
                        }
                        db.TAB.Task_Post.InsertOnSubmit(Post)
                        db.SubmitChanges()

                        If Not task.Share_All_Post Then
                            Exit For
                        End If

                    Next

                    'prendo il post + recente
                    Dim LastPost = SharePosts(0)

                    task.Share_Update = Date.UtcNow
                    task.Share_Update_Post_Code = LastPost.Post_Code
                    task.Share_Update_Post_Count = task.Share_Account.Account_Add_Info.Post_Update_Count   ' db.TAB.Account_Add_Info.GetByPK(task.Share_Account_Id).Post_Update_Count

                    db.SubmitChanges()

                    'IMPORTANTE dopo imposta il prossimo invio
                    task.SetNextSend()
                    db.SubmitChanges()


                End If


            End Sub


            'Private Shared Sub AddAccountPostsToTask(task As mDB.Task_Send)
            '    Dim db As mDB = mDB.GetDB
            '    Dim LastDate As Date = Date.MinValue
            '    Dim MaxPost = 100

            '    If task.Share_Update_Post_Code <> "" Then

            '        'Dim LastPost = db.TAB.AccountPost.BY.AccountPost.PostCode(task.Share_Update_Post_Code).ToObj
            '        Dim LastPost = task.Share_Account._Tab_Account_Post.BY._Account_Post._Post_Code(task.Share_Update_Post_Code).ToObj
            '        If LastPost IsNot Nothing Then
            '            LastDate = LastPost.Pubb_Date
            '        Else
            '            MaxPost = 1
            '        End If
            '    Else
            '        MaxPost = 1
            '    End If

            '    'prendo i post + nuovi rispetto all'ultimo
            '    'Dim SharePosts = db.TAB.AccountPost.
            '    '    BY.AccountPost.Account_Id(task.Share_Account_Id).
            '    '    Where("Pubb_Date", ">=", LastDate).
            '    '    OrderBy("Pubb_Date desc").
            '    '    Limit(MaxPost).
            '    'ToList()
            '    Dim SharePosts = task.Share_Account._Tab_Account_Post.
            '        Where("Pubb_Date", ">=", LastDate).
            '        OrderBy("Pubb_Date desc").
            '        Limit(MaxPost).
            '    ToList()

            '    'SharePosts = SharePosts.OrderBy(Function(o) o.Pubb_Date).ToList

            '    If SharePosts.Count > 0 Then
            '        MyApp.WriteProcLog(SF("(tab)(tab)begin share post account : {0}, post number: {1}", task.Share_Account_Id, SharePosts.Count), AutoProcType.UPDATE_POSTS)

            '        For Each p In SharePosts

            '            If p.Post_Code <> task.Share_Update_Post_Code Then
            '                MyApp.WriteProcLog(SF("(tab)(tab)(tab)share post code: {0}", p.Post_Code), AutoProcType.UPDATE_POSTS)


            '                Dim Post = New mDB.Task_Post With {
            '                    .Task_Send_Id = task.Id,
            '                    .Post_Text = p.Post_Text,
            '                    .Post_Type_Id = mDB.Task_Post.Type.SHARE,
            '                    .Share_Post_Code = p.Post_Code
            '                }
            '                db.TAB.Task_Post.InsertOnSubmit(Post)

            '                If Not task.Share_All_Post Then
            '                    Exit For
            '                End If

            '            End If

            '        Next


            '        'prendo il post + recente
            '        Dim LastPost = SharePosts(0)

            '        task.Share_Update_Date = Date.UtcNow
            '        task.Share_Update_Post_Code = LastPost.Post_Code
            '        task.Share_Update_Post_Count = db.TAB.Account_Update.GetByPK(task.Share_Account_Id).Post_Update_Count

            '        db.SubmitChanges()

            '        'IMPORTANTE dopo imposta il prossimo invio
            '        task.SetNextSend()
            '        db.SubmitChanges()


            '    End If


            'End Sub
#End Region

#Region "FEEDRSS"

            Public Shared Sub AddFeedRssToTask()
                Dim db As mDB = mDB.GetDB


                'AddPostShareToTask
                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN FEEDRSS", TaskType.UPDATE_POSTS)

                For Each Acc In Accounts

                    'trova tutti gli followers da agiornare i post
                    Dim Tasks = Acc.Tab_Task_Send.
                        REL.Task_Send.FeedRss.
                        Where("feedrss_item_id <> item_last_id").
                        Where("task_send.expired_task", "=", False).
                        Where("task_send.enabled_task", "=", True).
                        Where("task_send.feedrss_update", "<", Date.UtcNow.AddHours(-1)).
                        SetSelect("task_send.*").
                    ToList(Of mDB.Task_Send)()

                    If Tasks.Count > 0 Then

                        MyApp.WriteProcLog(SF("(tab)begin share post : {0}, account number: {1}", Acc.Fullname, Tasks.Count), TaskType.UPDATE_POSTS)

                        'tw.oauth = Acc.getOauth

                        For Each t In Tasks
                            'Dim LastPost = tw.SendShareAccountPost(al.Account_Link_Id, al.Update_Str)
                            AddFeedRssItemToTask(t)

                        Next

                    End If


                Next

                MyApp.WriteProcLog("END FEEDRSS", TaskType.UPDATE_POSTS)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.UPDATE_POSTS)


            End Sub

            Private Shared Sub AddFeedRssItemToTask(task As mDB.Task_Send)
                Dim db As mDB = mDB.GetDB
                Dim LastDate As Date = Date.MinValue
                Dim MaxPost = 100

                If task.Feedrss_Item_Id = 0 Then
                    MaxPost = 1
                End If

                'prendo i post + nuovi rispetto all'ultimo
                Dim FeesRssItems = db.TAB.Feedrss_Item.
                    BY.Feedrss_Item.Feedrss_Id(task.Feedrss_Id).
                    Where("id", ">", task.Feedrss_Item_Id).
                    OrderBy("id desc").
                    Limit(MaxPost).
                ToList()

                If FeesRssItems.Count > 0 Then
                    MyApp.WriteProcLog(SF("(tab)(tab)begin feed rss item : {0}, post number: {1}", task.Feedrss_Id, FeesRssItems.Count), TaskType.UPDATE_POSTS)

                    For Each p In FeesRssItems

                        If p.Id <> task.Feedrss_Item_Id Then
                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)feed rss item code: {0}", p.Id), TaskType.UPDATE_POSTS)


                            Dim Post = New mDB.Task_Post With {
                                .Task_Send_Id = task.Id,
                                .Post_Text = Mid(Utils.ClearHTML(p.Description), 1, 255) & " " & p.Link,
                                .Post_Type_Id = mDB.Task_Post.Type.NORMAL
                            }
                            db.TAB.Task_Post.InsertOnSubmit(Post)

                            'If Not task.Share_All_Post Then
                            '    Exit For
                            'End If

                        End If

                    Next


                    'prendo il post + recente
                    Dim LastPost = FeesRssItems(0)

                    task.Feedrss_Update = Date.UtcNow
                    task.Feedrss_Item_Id = LastPost.Id

                    db.SubmitChanges()

                    'IMPORTANTE dopo imposta il prossimo invio
                    task.SetNextSend()
                    db.SubmitChanges()


                End If


            End Sub

#End Region

#Region "AUTO POST"

            Public Shared Sub AddAutoPostToTask()

                Dim db As mDB = mDB.GetDB

                Dim Accounts = db.VIEW.Account_UserEnabled.
                    BY.Account_Auth.Network_id(Network.AccType.TWITTER_ACCOUNT).
                ToList()

                MyApp.WriteProcLog("BEGIN AUTO POST", TaskType.ELABORATE_DATA)

                For Each Acc In Accounts

                    'trova tutti i task abilitati non scaduti
                    Dim Tasks = Acc.Tab_Task_Send.
                        Where("task_send.auto_post_active", "=", True).
                        Where("task_send.expired_task", "=", False).
                        Where("task_send.enabled_task", "=", True).
                        Where("task_send.auto_post_last_update", "<", Date.UtcNow.AddHours(-1)).
                        SetSelect("task_send.*").
                    ToList

                    If Tasks.Count > 0 Then

                        'tw.oauth = Acc.getOauth

                        MyApp.WriteProcLog(SF("(tab)begin auto post : {0}, task: {1}", Acc.Fullname, Tasks.Count), TaskType.ELABORATE_DATA)

                        For Each t In Tasks

                            '-------------------------------------
                            ' AUTO POST su filtri utenti

                            If t.Auto_Post_Filter.IdsLink.Where(Function(o) o > 0).Count > 0 Then

                                'IMPORTANTE aggiorno i foll ogni 8 ore.. così sono sicuro che praticamente è stato verificato almeno 3 volte
                                Dim DateLimit = Date.UtcNow.AddHours(-17)

                                Dim AccountLink = Acc.View_AccountLink_ByFilter(t.Auto_Post_Filter).
                                    Where("create_date", "<", DateLimit).
                                    Where("create_date", ">", t.Auto_Post_Last_Update).
                                    OrderBy("create_date").
                                ToList(Of mDB.Account)()

                                If AccountLink.Count > 0 Then

                                    MyApp.WriteProcLog(SF("(tab)(tab)task: '{0}', account add: ({1}), link type: [{2}]", t.Description, AccountLink.Count, t.Auto_Post_Filter.IdsLink(0)), TaskType.ELABORATE_DATA)

                                    'verifico che tutti gli account abbiano lo username (cioè sono stati scaricati
                                    Dim AccNoUser = AccountLink.Where(Function(o) o.Username = "").ToList
                                    If AccNoUser.Count > 0 Then

                                        MyApp.WriteProcLog(SF("(tab)(tab)ERRORE account no user: ({0}), ex: [{1}]", AccNoUser.Count, AccNoUser(0).Id), TaskType.ELABORATE_DATA)

                                    Else

                                        Dim posttexts = t.Auto_Post_Text_List.Where(Function(o) o.Trim <> "").ToList
                                        Dim textsend = String.Join(TemplatePost.TemplateSeparator, posttexts)

                                        ' aggiungi i post
                                        Dim Post = New mDB.Task_Post With {
                                            .Post_Text = textsend,
                                            .Post_Type_Id = IIf(t.Auto_Post_Private, mDB.Task_Post.Type.PRIVATE, mDB.Task_Post.Type.NORMAL)
                                        }
                                        t.AddPosts(Post, AccountLink, True)

                                        'aggiorna il prossimo invio
                                        t.SetNextSend()

                                    End If

                                    t.Auto_Post_Last_Update = DateLimit 'Links(0).Create_Date
                                    db.SubmitChanges()

                                End If


                            End If

                            '---------------------------------------------
                            ' AUTO POST schedulati

                            If t.Auto_Post_Schedule_Type_Id <> 0 Then
                                Dim s As DateInterval = t.Auto_Post_Schedule_Type_Id

                                Dim addPost = False
                                Select Case s
                                    Case DateInterval.Day

                                        t.Auto_Post_Last_Update = Date.UtcNow.Date.AddDays(1).AddHours(3)
                                        addPost = True

                                    Case DateInterval.Weekday
                                        'DayOfWeek.Monday =1
                                        If Date.UtcNow.DayOfWeek = t.Auto_Post_Schedule_Detail Then

                                            t.Auto_Post_Last_Update = Date.UtcNow.Date.AddDays(7).AddHours(3)
                                            addPost = True

                                        End If

                                    Case DateInterval.Month
                                        If Date.UtcNow.Day = t.Auto_Post_Schedule_Detail Then

                                            t.Auto_Post_Last_Update = Date.UtcNow.Date.AddMonths(1).AddHours(3)
                                            addPost = True

                                        End If

                                End Select

                                If addPost Then

                                    Dim posttexts = t.Auto_Post_Text_List.Where(Function(o) o.Trim <> "").ToList
                                    Dim textsend = String.Join(TemplatePost.TemplateSeparator, posttexts)

                                    Dim Post = New mDB.Task_Post With {
                                        .Post_Text = textsend,
                                        .Post_Type_Id = mDB.Task_Post.Type.NORMAL
                                    }

                                    If t.AddPost(Post, Acc) Then
                                        'aggiorna il prossimo invio
                                        t.SetNextSend()
                                        MyApp.WriteProcLog(SF("(tab)(tab)task: '{0}', shed: [{1}];[{2}], post add: '{3}', ", t.Description, t.Auto_Post_Schedule_Type_Id, t.Auto_Post_Schedule_Detail, Post.Post_Text), TaskType.ELABORATE_DATA)

                                    Else

                                        MyApp.WriteProcLog(SF("(tab)(tab)task: '{0}', shed: [{1}];[{2}], post empty data: '{3}', ", t.Description, t.Auto_Post_Schedule_Type_Id, t.Auto_Post_Schedule_Detail, Post.Post_Text), TaskType.ELABORATE_DATA)

                                    End If

                                End If

                                db.SubmitChanges()

                            End If


                        Next

                    End If


                Next

                MyApp.WriteProcLog("END AUTO POST", TaskType.ELABORATE_DATA)
                MyApp.WriteProcLog("----------------------------------------------------------", TaskType.ELABORATE_DATA)


            End Sub



#End Region

        End Class

        Public Class TemplatePost

            Public Property Account As mDB.Account
            Public Property FromDate As Date
            Public Property ToDate As Date
            Public Property data As New Dictionary(Of String, Object)
            Public Property EmptyData As Boolean
            Public Shared Property TemplateSeparator As String = "{|}"

            Sub New()

                data.Add("{cr}", vbCrLf)


            End Sub

            Private Sub LoadData()

                EmptyData = False

                Dim kk = (From k In data Select k.Key).ToList

                For Each k In kk
                    If data(k) Is Nothing Then

                        Dim p = k.ToLower.Trim({"{"c, "}"c}).Split(";")
                        Select Case p(0)

                            Case "username"

                                data(k) = Account.Username

                            Case "fullname"

                                data(k) = Account.Fullname

                            Case "location"

                                data(k) = Account.Location

                            Case "url"

                                data(k) = Account.Url

                            Case "post"

                                If p.Length > 1 Then
                                    Me.SetDate(p(1))
                                    data(k) = Account.GetTrendSum(mDB._Trend.Type.POST_REL, Me.FromDate, Me.ToDate)
                                Else
                                    data(k) = Account.Account_Add_Info.Post_Count
                                End If


                            Case "followers"

                                If p.Length > 1 Then
                                    Me.SetDate(p(1))
                                    data(k) = Account.GetAccountLinkCount(mDB._Account_Link.Type.FOLLOWER, Me.FromDate, Me.ToDate)
                                Else
                                    data(k) = Account.Account_Add_Info.Follower_Count
                                End If


                            Case "friends"

                                If p.Length > 1 Then
                                    Me.SetDate(p(1))
                                    data(k) = Account.GetAccountLinkCount(mDB._Account_Link.Type.FRIENDS, Me.FromDate, Me.ToDate)
                                Else
                                    data(k) = Account.Account_Add_Info.Friend_Count
                                End If

                                '----------------------------------------------------------
                                ' STATISTICHE

                            Case "male_perc"

                                Dim Male = Account.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.GENDER, mDB.Gender_Name.Type.MALE)
                                Dim Female = Account.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.GENDER, mDB.Gender_Name.Type.FEMALE)
                                data(k) = UI.Print.Num0(Utils.Math.Perc(Male, Male + Female)) & "%"


                            Case "female_perc"

                                Dim Male = Account.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.GENDER, mDB.Gender_Name.Type.MALE)
                                Dim Female = Account.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.GENDER, mDB.Gender_Name.Type.FEMALE)
                                data(k) = UI.Print.Num0(Utils.Math.Perc(Female, Male + Female)) & "%"


                            Case "business_perc"

                                Dim TotBusiness = Account.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.BUSINESS, mDB.Account.BusinessType.BUSINESS)
                                Dim TotPrivate = Account.GetFollowerAnalysisValue(mDB.Follower_Analysis.Type.BUSINESS, mDB.Account.BusinessType.PRIVATE)
                                data(k) = UI.Print.Num0(Utils.Math.Perc(TotBusiness, TotBusiness + TotPrivate)) & "%"

                                '----------------------------------------------------------
                                ' LISTE USER

                            Case "most_engaging"

                                Me.SetDate(p(1))

                                Dim InterAccs = Account.GetInterractionAccount(Me.FromDate, Me.ToDate.AddDays(1))

                                Dim Ids = (From a In InterAccs Order By a.Value Descending Select a.Key Take 3).ToList

                                If Ids.Count > 0 Then
                                    Dim Accs = mDB.GetDB.TAB.Account.
                                        Where("id", "IN", Ids).ToList

                                    data(k) = String.Join(" ", Accs.Select(Function(o) "@" & o.Username).ToArray)
                                End If

                            Case "last_followers"

                                Me.SetDate(p(1))

                                Dim accs = Account._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER, Me.FromDate, Me.ToDate).
                                    REL._Account_Link.Account.
                                    OrderBy("create_date").
                                    Limit(5).
                                ToList(Of mDB.Account)()

                                data(k) = String.Join(" ", accs.Select(Function(o) "@" & o.Username).ToArray)



                        End Select


                    End If
                Next

            End Sub
            Private Function ToInterval(i As String) As DateInterval

                Select Case i.ToLower
                    Case "d"
                        Return DateInterval.Day
                    Case "w"
                        Return DateInterval.Weekday
                    Case "m"
                        Return DateInterval.Month
                    Case "q"
                        Return DateInterval.Quarter
                    Case Else
                        Return DateInterval.Day

                End Select

            End Function
            Private Sub SetDate(i As String)

                SetDate(ToInterval(i))

            End Sub
            Private Sub SetDate(i As DateInterval)

                Select Case i
                    Case DateInterval.Day
                        Me.ToDate = Date.UtcNow.Date.AddDays(-1)
                        Me.FromDate = Date.UtcNow.Date.AddDays(-1)

                    Case DateInterval.Weekday
                        Me.ToDate = Date.UtcNow.Date.AddDays(-1)
                        Me.FromDate = Date.UtcNow.Date.AddDays(-7)

                    Case DateInterval.Month
                        Me.ToDate = Date.UtcNow.Date.AddDays(-1)
                        Me.FromDate = Date.UtcNow.Date.AddMonths(-1)

                    Case DateInterval.Quarter
                        Me.ToDate = Date.UtcNow.Date.AddDays(-1)
                        Me.FromDate = Date.UtcNow.Date.AddMonths(-3)

                End Select

            End Sub

            'Private Function GetTrendValue(t As mDB.Trend.Type) As Integer

            '    Return Account.GetTrendSum(t, Me.FromDate, ToDate)

            'End Function

            Public Function Render(PostTpl As String) As String

                Randomize()
                Dim tpls = PostTpl.Split({TemplateSeparator}, StringSplitOptions.RemoveEmptyEntries)
                Dim t = tpls((New Random(Convert.ToInt32(Rnd() * Int32.MaxValue))).Next(tpls.Count))


                Dim mats = Regex.Matches(t, "{[\S]*}")

                For Each m As Match In mats

                    If Not data.ContainsKey(m.Value) Then
                        data.Add(m.Value, Nothing)
                    End If

                Next

                Me.LoadData()

                Dim tmp = t
                For Each m As Match In mats

                    If data(m.Value) IsNot Nothing Then
                        tmp = tmp.Replace(m.Value, data(m.Value))
                    Else
                        Me.EmptyData = True
                    End If

                Next

                Return tmp

            End Function


        End Class


        Public Class ScheduleTask

            Property Uri As Uri
            Property SecondInterval As Integer
            Property Execute As Boolean
            'Property AlreadyExecute As Boolean

            Property Label As String

            Dim timer As System.Timers.Timer

            Sub start()

                timer = New System.Timers.Timer(SecondInterval * 1000)
                timer.AutoReset = True
                timer.Enabled = True
                AddHandler timer.Elapsed, AddressOf timer_Elapsed

                Label &= " - " & Guid.NewGuid.ToString

                Execute = False

                timer.Start()

            End Sub

            Sub StopTask()

                timer.Stop()

            End Sub


            Sub timer_Elapsed(sender As Object, a As System.Timers.ElapsedEventArgs)

                If Execute Then
                    MyApp.WriteProcLog(SF("(tab)in progress: {0}, url: {1}", Label, Uri.AbsoluteUri), MyApp.Task.TaskType.SCHEDULE)
                    Exit Sub
                End If

                '' MAKE URL
                Dim ub As New UriBuilder(Me.Uri)
                Dim queryString = HttpUtility.ParseQueryString(ub.Query)

                'If Not AlreadyExecute Then
                '    'queryString.Add("i", "ok")
                'End If
                ub.Query = queryString.ToString
                Dim uritemp = ub.Uri


                Execute = True
                'AlreadyExecute = True

                Dim webclient As New WebApi.Net.WebClient

                MyApp.WriteProcLog(SF("request: {0}, url: {1}", Label, Uri.AbsoluteUri), MyApp.Task.TaskType.SCHEDULE)

                webclient.Timeout = -1 ' 1000 * 60 * 60 * 24 'Integer.MaxValue
                Try

                    webclient.DownloadData(uritemp)
                    'Threading.Thread.Sleep(3000)

                Catch ex As Exception
                    MyApp.WriteProcLog(SF("(tab)response: {0}, err: {2}, url: {1}", Label, Uri.AbsoluteUri, ex.Message), MyApp.Task.TaskType.SCHEDULE)

                End Try

                MyApp.WriteProcLog(SF("(tab)response: {0}, status: {2}, url: {1}", Label, Uri.AbsoluteUri, webclient.StatusCode), MyApp.Task.TaskType.SCHEDULE)

                ''webclient.StatusCode

                Execute = False

            End Sub

            Public Shared Sub Update(a As MyApp.Task.TaskType, s As MyApp.Task.TaskStatusType, d As Date, res As String)

                Dim TrayCount = 0

                Do
                    Try

                        Dim db = mDB.GetDB
                        'db.ResetChanges()

                        Dim t = db.TAB.Schedule_Task.GetByPK(a)

                        If t Is Nothing Then
                            t = New mDB.Schedule_Task With {.Id = a, .Name = a.ToString}
                            db.TAB.Schedule_Task.InsertOnSubmit(t)
                        End If

                        If s = MyApp.Task.TaskStatusType.READY Then
                            t.Stop_Date = d
                            t.Last_Result = res
                        Else
                            t.Start_Date = d

                        End If

                        t.Status_Id = s
                        t.Status = s.ToString

                        db.SubmitChanges()

                        TrayCount = 0

                    Catch ex As Exception

                        TrayCount += 1

                        If TrayCount > 3 Then
                            Throw ex
                        Else
                            MyApp.WriteProcLog(SF("ERROR SCHEDULE UPDATE: {0}, count: {1}, Err: {2}", a.ToString, TrayCount, ex.Message), MyApp.Task.TaskType.DEBUG)

                        End If

                    End Try
                Loop Until TrayCount = 0

            End Sub


        End Class


    End Namespace

    Namespace Network
        Public Module LibGlobal

            Public Function AccTypeToNetType(a As Network.AccType) As WebApi.Type

                Select Case a
                    Case Network.AccType.TWITTER_ACCOUNT
                        Return WebApi.Type.TWITTER
                    Case Network.AccType.FACEBOOK_USER, Network.AccType.FACEBOOK_PAGE
                        Return WebApi.Type.FACEBOOK
                    Case Network.AccType.LINKEDIN_PEOPLE, Network.AccType.LINKEDIN_COMPANY
                        Return WebApi.Type.LINKEDIN
                    Case AccType.GOOGLE_PEOPLE, AccType.GOOGLE_PAGE
                        Return WebApi.Type.GOOGLE
                    Case AccType.BUFFER
                        Return WebApi.Type.BUFFER
                    Case Else
                        Return -1
                End Select

            End Function
            Public Function NetTypeToAccTypes(n As WebApi.Type) As Network.AccType()

                Select Case n
                    Case WebApi.Type.TWITTER
                        Return New Network.AccType() {Network.AccType.TWITTER_ACCOUNT}
                    Case WebApi.Type.FACEBOOK
                        Return New Network.AccType() {Network.AccType.FACEBOOK_USER, Network.AccType.FACEBOOK_PAGE}
                    Case WebApi.Type.LINKEDIN
                        Return New Network.AccType() {Network.AccType.LINKEDIN_PEOPLE, Network.AccType.LINKEDIN_COMPANY}
                    Case WebApi.Type.GOOGLE
                        Return New Network.AccType() {Network.AccType.GOOGLE_PEOPLE, Network.AccType.GOOGLE_PAGE}
                    Case WebApi.Type.BUFFER
                        Return New Network.AccType() {Network.AccType.BUFFER}
                    Case Else
                        Return New Network.AccType() {}

                End Select

            End Function

        End Module
        Public Class NetProperty

            Public Property Available As New DataAvailable

            Public Property App As New DataApp


            Public Class DataApp
                Public Property SocialSeo As Boolean = True
                Public Property AutoFollow As Boolean = True
            End Class

            Public Class DataAvailable
                Public Property AccountFollowersCount As Boolean = True
                Public Property AccountGeoLocate As Boolean = True
            End Class


        End Class



        Public Enum AccType
            TWITTER_ACCOUNT = 100
            FACEBOOK_USER = 200
            FACEBOOK_PAGE = 201
            GOOGLE_PEOPLE = 300
            GOOGLE_PAGE = 301
            LINKEDIN_PEOPLE = 400
            LINKEDIN_COMPANY = 401
            INSTAGRAM_ACCOUNT = 500
            BUFFER = 600
            KLOUK = 700
        End Enum


        Public Class OpenstreetMap

            'Public Property oauth As WebApi.Oauth.Oauth
            Public Property HttpContextCurrent() As HttpContext

            Private db As mDB = mDB.GetDB


            Public Sub DownloadPlace(Acc As mDB.Account)
                Dim tc As New WebApi.OpenstreetMap.OpenstreetMapClient

                Try

                    Dim p As List(Of WebApi.OpenstreetMap.Place) = Nothing
                    If Acc.Location.Trim <> "" Then
                        p = tc.GetGeoSearch(Acc.Location)
                    End If

                    UpdateAccountPlaces(Acc, p)

                    Threading.Thread.Sleep(0)

                Catch ex As Exception

                    MyApp.WriteProcLog(SF("(tab)(tab)error update place: Exception: {0}", ex.Message), MyApp.Task.TaskType.UPDATE_ACCOUNTS)

                End Try


            End Sub
            Public Sub UpdateAccountPlaces(Acc As mDB.Account, p As List(Of WebApi.OpenstreetMap.Place))


                Dim SelectPlaceName As String = "Nothing"
                Dim SelectPlace As mDB.Place = Nothing
                Dim SelectPlaceID = -1

                If p IsNot Nothing AndAlso p.Count > 0 Then

                    SelectPlace = UpdatePlace(p(0), True)

                    If SelectPlace IsNot Nothing Then
                        SelectPlaceName = SelectPlace.Name
                        SelectPlaceID = SelectPlace.Id
                    End If

                End If

                Acc.Account_Add_Info.Place_Id = SelectPlaceID
                db.SubmitChanges()

                MyApp.WriteProcLog(SF("(tab)(tab)update place: {0},user location: {1}, found place: {2}", Acc.Fullname, Acc.Location, SelectPlaceName), Task.TaskType.UPDATE_ACCOUNTS)


            End Sub
            Public Sub DownloadPlace(Query As mDB.Query)
                Dim tc As New WebApi.OpenstreetMap.OpenstreetMapClient

                Try

                    Dim p As List(Of WebApi.OpenstreetMap.Place) = Nothing

                    If Query.Place <> "" Then
                        p = tc.GetGeoSearch(Query.Place)
                    End If

                    UpdateQueyPlaces(Query, p)

                    Threading.Thread.Sleep(0)

                Catch ex As Exception

                    MyApp.WriteProcLog(SF("(tab)(tab)error update place: Exception: {0}", ex.Message), Task.TaskType.UPDATE_ACCOUNTS)

                End Try


            End Sub
            Public Sub UpdateQueyPlaces(Query As mDB.Query, p As List(Of WebApi.OpenstreetMap.Place))


                Dim SelectPlaceName As String = "Nothing"
                Dim SelectPlace As mDB.Place = Nothing
                Dim SelectPlaceID = -1

                If p IsNot Nothing AndAlso p.Count > 0 Then

                    SelectPlace = UpdatePlace(p(0), True)

                    If SelectPlace IsNot Nothing Then
                        SelectPlaceName = SelectPlace.Name
                        SelectPlaceID = SelectPlace.Id
                    End If

                End If

                Query.Place_Id = SelectPlaceID
                db.SubmitChanges()

                MyApp.WriteProcLog(SF("(tab)(tab)update place: {0},user location: {1}, found place: {2}", Query.Query, Query.Place, SelectPlaceName), Task.TaskType.UPDATE_QUERY)


            End Sub
            Public Function UpdatePlace(place As WebApi.OpenstreetMap.Place, UpdateCountry As Boolean) As mDB.Place

                Dim p = db.TAB.Place.BY.Place.Place_Code(place.place_id).ToObj

                If p Is Nothing Then
                    p = New mDB.Place
                    db.TAB.Place.InsertOnSubmit(p)
                End If

                p.Place_Code = place.place_id
                p.Name = Mid(place.display_name, 1, 255)
                p.Place_Type = place.type

                p.Lat = place.lat
                p.Lon = place.lon
                p.Accuracy = place.importance

                If place.boundingbox IsNot Nothing Then
                    If place.boundingbox.Count > 0 Then
                        p.Bounding_Box = MyApp.JSONSerialize(place.boundingbox)
                    End If
                End If

                If place.address IsNot Nothing Then
                    p.Country_Code = place.address.country_code
                    p.Country = place.address.country
                    p.State = place.address.state
                    p.County = place.address.county
                    p.City = place.address.city
                    p.Locality = place.address.locality

                    'If p.State = "" Or (p.State = place.address.country) Then
                    '    p.Place_Type = "country"
                    'End If
                End If

                db.SubmitChanges()

                'If p.Place_Type <> "country" And UpdateCountry Then

                '    'verifica se esiste il contry
                '    Dim CountryP = db.TAB.Place.BY.Place.CountryCode(place.address.country_code).Where("place_type", "=", "country").ToObj
                '    If CountryP Is Nothing Then
                '        Dim tc As New WebApi.OpenstreetMap.OpenstreetMapClient
                '        Dim CountryPlace = tc.GetGeoSearch(place.address.country).ToList(0)

                '        UpdatePlace(CountryPlace, False)

                '    End If
                'End If


                Return p

            End Function


        End Class

        Public Class FeedRss

            Private db As mDB = mDB.GetDB

            Public Sub DownloadRss(f As mDB.Feedrss)
                Dim fc As New WebApi.FeedRss.FeedRssClient
                Dim LastID As Integer

                fc.lastmod = f.Last_Modified
                fc.etag = f.Etag

                Dim feed = fc.GetFeed(f.Url)

                If feed IsNot Nothing Then

                    MyApp.WriteProcLog(SF("(tab)(tab)update feedrss: {0}, number item: {1}", f.Url, feed.Items.Count), Task.TaskType.UPDATE_ACCOUNTS)


                    For Each i In feed.Items

                        Dim StringToHash = i.Id
                        If StringToHash = "" Then
                            StringToHash = i.Summary.Text & i.Title.Text
                        End If

                        StringToHash = Utils.MD5.MD5(StringToHash & f.Url)

                        Dim fitem = db.TAB.Feedrss_Item.BY.Feedrss_Item.Hash(StringToHash).ToObj

                        If fitem Is Nothing Then
                            fitem = New mDB.Feedrss_Item With {
                                .Description = i.Summary.Text,
                                .Title = i.Title.Text,
                                .Feedrss_Id = f.Id,
                                .Hash = StringToHash
                            }

                            If i.Links.Count > 0 Then
                                fitem.Link = i.Links(0).Uri.AbsoluteUri
                            End If

                            db.TAB.Feedrss_Item.InsertOnSubmit(fitem)
                            db.SubmitChanges()


                        End If

                        LastID = fitem.Id
                    Next


                    f.Last_Modified = fc.lastmod
                    f.Etag = fc.etag
                    f.Item_Last_Id = LastID
                    f.Item_Update = Date.UtcNow
                    db.SubmitChanges()
                Else

                    MyApp.WriteProcLog(SF("(tab)(tab)update feedrss: not change"), Task.TaskType.UPDATE_ACCOUNTS)


                End If




            End Sub


        End Class


        Public Class Klout

            Public Property oauth2 As WebApi.Oauth.Oauth2
            Public Property HttpContextCurrent() As HttpContext

            Private db As mDB = mDB.GetDB

            Public Sub New()
                oauth2 = New WebApi.Oauth.Oauth2(AccType.KLOUK)
                oauth2.access_token = "6yjzuasjhnkeh6b8ccmt3svf"

            End Sub


            Public Sub DownloadAccount(Acc As mDB.Account)
                Dim tc As New WebApi.Klout.KloutClient(Me.oauth2)

                Try

                    Dim i = tc.GetIdentityTwitterId(Acc.Account_Code)
                    Dim u = tc.GetShowUser(i.id)
                    Dim t = tc.GetTopics(i.id)

                    MyApp.WriteProcLog(SF("(tab)(tab)update user: {0},score: {1}, topics: ({2})", Acc.ToString, u.score.score, t.Count), Task.TaskType.UPDATE_ACCOUNTS)

                    UpdateAccount(Acc, u, t)

                Catch ex As WebApi.Net.ExceptionAPIResponse

                    UpdateAccount(Acc, New WebApi.Klout.User, New List(Of WebApi.Klout.Topic))

                End Try



            End Sub
            Public Sub UpdateAccount(Acc As mDB.Account, u As WebApi.Klout.User, t As List(Of WebApi.Klout.Topic))

                Dim acck = db.TAB.Account_Klout.GetByPK(Acc.Id)
                If acck Is Nothing Then
                    acck = New mDB.Account_Klout With {.Account_Id = Acc.Id}
                    db.TAB.Account_Klout.InsertOnSubmit(acck)
                End If

                acck.Klout_Code = u.kloutId
                If u.score IsNot Nothing Then
                    acck.Score = u.score.score
                End If

                acck.Topics = String.Join(" - ", t.Select(Function(o) o.displayName))


                db.SubmitChanges()

            End Sub
            'Public Sub DownloadPlace(Query As mDB.Query)
            '    Dim tc As New WebApi.OpenstreetMap.OpenstreetMapClient

            '    Try

            '        Dim p As List(Of WebApi.OpenstreetMap.Place) = Nothing

            '        If Query.Place <> "" Then
            '            p = tc.GetGeoSearch(Query.Place)
            '        End If

            '        UpdateQueyPlaces(Query, p)

            '        Threading.Thread.Sleep(0)

            '    Catch ex As Exception

            '        MyApp.WriteProcLog(SF("(tab)(tab)error update place: Exception: {0}", ex.Message), Task.TaskType.UPDATE_ACCOUNTS)

            '    End Try


            'End Sub
            'Public Sub UpdateQueyPlaces(Query As mDB.Query, p As List(Of WebApi.OpenstreetMap.Place))


            '    Dim SelectPlaceName As String = "Nothing"
            '    Dim SelectPlace As mDB.Place = Nothing
            '    Dim SelectPlaceID = -1

            '    If p IsNot Nothing AndAlso p.Count > 0 Then

            '        SelectPlace = UpdatePlace(p(0), True)

            '        If SelectPlace IsNot Nothing Then
            '            SelectPlaceName = SelectPlace.Name
            '            SelectPlaceID = SelectPlace.Id
            '        End If

            '    End If

            '    Query.Place_Id = SelectPlaceID
            '    db.SubmitChanges()

            '    MyApp.WriteProcLog(SF("(tab)(tab)update place: {0},user location: {1}, found place: {2}", Query.Query, Query.Place, SelectPlaceName), Task.TaskType.UPDATE_QUERY)


            'End Sub
            'Public Function UpdatePlace(place As WebApi.OpenstreetMap.Place, UpdateCountry As Boolean) As mDB.Place

            '    Dim p = db.TAB.Place.BY.Place.Place_Code(place.place_id).ToObj

            '    If p Is Nothing Then
            '        p = New mDB.Place
            '        db.TAB.Place.InsertOnSubmit(p)
            '    End If

            '    p.Place_Code = place.place_id
            '    p.Name = Mid(place.display_name, 1, 255)
            '    p.Place_Type = place.type

            '    p.Lat = place.lat
            '    p.Lon = place.lon
            '    p.Accuracy = place.importance

            '    If place.boundingbox IsNot Nothing Then
            '        If place.boundingbox.Count > 0 Then
            '            p.Bounding_Box = MyApp.JSONSerialize(place.boundingbox)
            '        End If
            '    End If

            '    If place.address IsNot Nothing Then
            '        p.Country_Code = place.address.country_code
            '        p.Country = place.address.country
            '        p.State = place.address.state
            '        p.County = place.address.county
            '        p.City = place.address.city
            '        p.Locality = place.address.locality

            '        'If p.State = "" Or (p.State = place.address.country) Then
            '        '    p.Place_Type = "country"
            '        'End If
            '    End If

            '    db.SubmitChanges()

            '    'If p.Place_Type <> "country" And UpdateCountry Then

            '    '    'verifica se esiste il contry
            '    '    Dim CountryP = db.TAB.Place.BY.Place.CountryCode(place.address.country_code).Where("place_type", "=", "country").ToObj
            '    '    If CountryP Is Nothing Then
            '    '        Dim tc As New WebApi.OpenstreetMap.OpenstreetMapClient
            '    '        Dim CountryPlace = tc.GetGeoSearch(place.address.country).ToList(0)

            '    '        UpdatePlace(CountryPlace, False)

            '    '    End If
            '    'End If


            '    Return p

            'End Function


        End Class




        'AccountUpdate


        'Public Sub fff()

        'End Sub



    End Namespace

    Namespace Email

        Public Module LibGlobal

            Public Sub Send(from As String, Recipients As String, Subject As String, Message As String)

                If UI.Validator.DataValidator.Email(Recipients) Then

                    Dim mmm As New Net.Mail.MailMessage
                    mmm.IsBodyHtml = True
                    mmm.From = New Net.Mail.MailAddress(from)
                    mmm.To.Add(New Net.Mail.MailAddress(Recipients))
                    mmm.Subject = Subject
                    mmm.Body = Message

                    Dim smtp = New Net.Mail.SmtpClient("smtp.mandrillapp.com", 587)

                    smtp.UseDefaultCredentials = False
                    smtp.EnableSsl = False
                    smtp.Credentials = New Net.NetworkCredential("evolvo.net@gmail.com", "8dXavNoRJKpaNq1FS0P6ZQ")


                    smtp.Send(mmm)

                End If

            End Sub




        End Module

        Public Class Template

            Public Property Data As TplData
            Public Property Tpl As String
            Public Property MasterTpl As String


            Public Sub New(fileVPath As String, Data As TplData)
                Me.Tpl = IO.File.ReadAllText(HttpContext.Current.Server.MapPath(fileVPath))
                Me.Data = Data
            End Sub

            Public Sub New(MasterVPath As String, fileVPath As String, Data As TplData)

                Me.New(fileVPath, Data)
                Me.MasterTpl = IO.File.ReadAllText(HttpContext.Current.Server.MapPath(MasterVPath))
                'Me.Tpl = IO.File.OpenText(HttpContext.Current.Server.MapPath(fileVPath)).ReadToEnd
                'Me.Data = Data
            End Sub


            Public Function Render() As String


                Dim mats = Regex.Matches(Tpl, "{{[\S]*}}")

                Dim tmp = Tpl
                For Each m As Match In mats

                    Dim key = m.Value.Trim({"{"c, "}"c})

                    If Data.ContainsKey(key) Then
                        tmp = tmp.Replace(m.Value, Data(key))
                    Else
                        tmp = tmp.Replace(m.Value, "")

                    End If
                Next


                If Me.MasterTpl <> "" Then
                    tmp = Me.MasterTpl.Replace("{{content}}", tmp)
                End If

                Return tmp

            End Function

            Public Class TplData
                Inherits Dictionary(Of String, String)
            End Class

        End Class
        Public Class System

            Public Shared Sender As String = "Glouk <no-reply@glouk.it>"

            Public Enum Type
                USER_REGISTER = 101
                USER_CONFIRM_EMAIL = 102
                USER_FORGOTTEN_PWD = 103
                QUERY_DOWNLOADED = 201
                ACCOUNT_ADD_TREND = 301
            End Enum


            Public Shared Function Queued(t As Type, send As Boolean, data As Object) As Boolean

                Dim db = mDB.GetDB
                Dim mm = New mDB.Send_Mail With {.Mail_Type = t, .Data_Json = MyApp.JSONSerialize(data)}

                db.InsertOnSubmit(mm)
                db.SubmitChanges()

                If send Then
                    Return mm.SendMail()
                Else
                    Return True

                End If

            End Function

            Public Shared Sub Send(t As Type, data As Object)
                Dim db = mDB.GetDB


                Select Case t
                    Case Type.USER_REGISTER

                        Dim User = db.TAB.User.GetByPK(data("user_id"))
                        Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/Register.html", New Template.TplData From {
                            {"user_name", User.Name}, {"user_email", User.Email}, {"user_password", User.Password},
                            {"user_link_email_confirm", SF("http://{0}/site/register.aspx?key={1}&email={2}", HttpContext.Current.Request.Url.Host, Utils.MD5.MD5Create(User.Email), User.Email)}
                        })

                        Email.Send(Sender, User.Email, "Glouk: Register user", tt.Render)
                        Email.Send(Sender, "evolvo.net@gmail.com", "Glouk: Register user", tt.Render)

                    Case Type.USER_CONFIRM_EMAIL

                        Dim User = db.TAB.User.GetByPK(data("user_id"))
                        Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/ConfirmEmail.html", New Template.TplData From {
                            {"user_name", User.Name},
                            {"user_email", User.Email},
                            {"user_password", User.Password},
                            {"user_link_email_confirm", SF("http://{0}/site/register.aspx?key={1}&email={2}", HttpContext.Current.Request.Url.Host, Utils.MD5.MD5Create(User.Email), User.Email)}
                        })

                        Email.Send(Sender, User.Email, "Glouk: Please confirm your email address", tt.Render)

                    Case Type.USER_FORGOTTEN_PWD

                        Dim User = db.TAB.User.GetByPK(data("user_id"))
                        Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/ForgottenPwd.html", New Template.TplData From {
                            {"user_name", User.Name},
                            {"user_email", User.Email},
                            {"user_password", User.Password},
                            {"user_link_email_confirm", SF("http://{0}/site/register.aspx?key={1}&email={2}", HttpContext.Current.Request.Url.Host, Utils.MD5.MD5Create(User.Email), User.Email)}
                        })

                        Email.Send(Sender, User.Email, "Glouk: Forgotten password", tt.Render)

                    Case Type.QUERY_DOWNLOADED
                        Dim Query = db.TAB.Query.GetByPK(data("query_id"))
                        If Query.Folder IsNot Nothing Then
                            Dim User = Query.Folder.User

                            Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/QueryDowloaded.html", New Template.TplData From {
                                {"user_name", User.Name},
                                {"query_query", Query.Query},
                                {"query_post_count", Query.Post_Count}
                            })

                            If User.Email = "gabriele@weevo.it" Or User.Email = "evolvo.net@gmail.com" Then
                                Email.Send(Sender, User.Email, "Glouk: Enquiry downloaded", tt.Render)
                                Email.Send(Sender, "evolvo.net@gmail.com", "Glouk: Enquiry downloaded", tt.Render)

                            End If
                        End If

                    Case Type.ACCOUNT_ADD_TREND
                        Dim Account = db.TAB.Account.GetByPK(data("account_id"))

                        Dim user = Account.Tab_User_Account.REL.User_Account.User.ToObj(Of mDB.User)()

                        Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/AccountAddTrend.html", New Template.TplData From {
                            {"user_name", user.Name},
                            {"account_fullname", Account.Fullname},
                            {"account_avatar", Account.Avatar},
                            {"account_description", Account.Description}
                        })

                        If user.Email = "gabriele@weevo.it" Or user.Email = "evolvo.net@gmail.com" Then
                            Email.Send(Sender, user.Email, "Glouk: Data account updated", tt.Render)
                            Email.Send(Sender, "evolvo.net@gmail.com", "Glouk: Data account updated", tt.Render)
                        End If

                End Select


            End Sub

        End Class
        Public Class Debug

            Public Shared Sub Send(message As String)

                Send(message, "")

            End Sub

            Public Shared Sub Send(message As String, recipients As String)

                'Dim smtp = New Net.Mail.SmtpClient("smtp.mandrillapp.com", 587)

                'smtp.UseDefaultCredentials = False
                'smtp.EnableSsl = False
                'smtp.Credentials = New Net.NetworkCredential("evolvo.net@gmail.com", "8dXavNoRJKpaNq1FS0P6ZQ")

                Email.Send("dev@glouk.it", "evolvo.net@gmail.com", "[GLOUK DEBUG]", message)

                'If (New UI.Validator.Validators.EmailValidator With {.Value = recipients}).Validate.GetByType(UI.Validator.ValidatorResultType.Error).Count = 0 Then
                '    smtp.Send("dev@glouk.it", recipients, "[GLOUK DEBUG]", message)
                'End If

                If UI.Validator.DataValidator.Email(recipients) Then
                    Email.Send("dev@glouk.it", recipients, "[GLOUK DEBUG]", message)
                End If

            End Sub

        End Class

        'Namespace Send2





        '    Public Class User

        '        Public Shared Sender As String = "Glouk <no-reply@glouk.it>"

        '        Public Shared Sub Register(User As mDB.User)

        '            Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/Register.html", New Template.TplData From {
        '                {"user_name", User.Name},
        '                {"user_email", User.Email},
        '                {"user_password", User.Password},
        '                {"user_link_email_confirm", SF("http://{0}/site/register.aspx?key={1}&email={2}", HttpContext.Current.Request.Url.Host, Utils.MD5.MD5Create(User.Email), User.Email)}
        '            })

        '            Send.Mail(Sender, User.Email, "Glouk: Register user", tt.Render)
        '            Send.Mail(Sender, "evolvo.net@gmail.com", "Glouk: Register user", tt.Render)

        '        End Sub

        '        Public Shared Sub ConfirmEmail(User As mDB.User)

        '            Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/ConfirmEmail.html", New Template.TplData From {
        '                {"user_name", User.Name},
        '                {"user_email", User.Email},
        '                {"user_password", User.Password},
        '                {"user_link_email_confirm", SF("http://{0}/site/register.aspx?key={1}&email={2}", HttpContext.Current.Request.Url.Host, Utils.MD5.MD5Create(User.Email), User.Email)}
        '            })

        '            Send.Mail(Sender, User.Email, "Glouk: Please confirm your email address", tt.Render)

        '        End Sub

        '        Public Shared Sub ForgottenPwd(User As mDB.User)

        '            Dim tt As New Template("~/App/Email/Template.html", "~/App/Email/ForgottenPwd.html", New Template.TplData From {
        '                {"user_name", User.Name},
        '                {"user_email", User.Email},
        '                {"user_password", User.Password},
        '                {"user_link_email_confirm", SF("http://{0}/site/register.aspx?key={1}&email={2}", HttpContext.Current.Request.Url.Host, Utils.MD5.MD5Create(User.Email), User.Email)}
        '            })

        '            Send.Mail(Sender, User.Email, "Glouk: Forgotten password", tt.Render)

        '        End Sub

        '    End Class


        'End Namespace


    End Namespace

End Namespace